user1418018
user1418018

Reputation: 189

Pass variables from Android Activity to JavaScript

Say I have two variables, x and y and I want to pass them from MyActivity to JavaScript. Here's my code:

public class myNewActivity extends Activity {
    double x;
    double y;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new);

        // get extras passed from another activity
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            x = extras.getDouble("x");
            y = extras.getDouble("y");
        }

        WebView webView = (WebView)findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebChromeClient(new WebChromeClient());
        //webView.loadUrl("javascript:setX('"+x+"')");
        //webView.loadUrl("javascript:setY('"+y+"')");
        webView.loadUrl("file:///android_asset/index.html");    
    }

I was trying something with the two commented lines but was just crashing the app. This is the JavaScript:

var x, y;
    function init(){
        // ... here I need the values of X and Y

    }
    function setX(ex) {
        x = ex;
    }
    function setY(ey) {
        y = ey
    }

Upvotes: 0

Views: 1867

Answers (1)

Biraj Zalavadia
Biraj Zalavadia

Reputation: 28484

You need to implement javascriptinteface in webview like this;

WebView webView = (WebView) findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new WebChromeClient());

    Bundle extras = getIntent().getExtras();
    double x = 0, y = 0;
    if (extras != null) {
        x = extras.getDouble("x");
        y = extras.getDouble("y");
    }
    webView.addJavascriptInterface(new JavaScriptInterface(x, y), "JSInterface");
    webView.loadUrl("file:///android_asset/index.html");

Create This Javainteface in your activity

public class JavaScriptInterface {

        double x, y;

        JavaScriptInterface(double x, double y) {
            this.x = x;
            this.y = y;
        }

        public double getXValue() {
            return x;
        }

        public double getYValue() {
            return y;

        }
    }

In you index.html

var x, y;
    function init(){
       x = JSInterface.getXValue();
       y = JSInterface.getYValue();
    }

Upvotes: 2

Related Questions