假设我有两个变量,x和y,我想将它们从MyActivity传递给JavaScript。这是我的代码:

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");
    }


我在两条注释行中尝试了一些操作,但是崩溃了。这是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
    }

最佳答案

您需要像这样在webview中实现javascriptinteface;

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");


在您的活动中创建此Javainteface

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;

        }
    }


在你的index.html

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

关于javascript - 将变量从Android Activity传递到JavaScript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23556794/

10-09 23:40