android java和js交互

android本地java代码和javascript的交互

java调用js

  • 通用设置
        mWebView = (WebView) findViewById(R.id.web_view);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(this, "jsbridge");
        mWebView.loadUrl("file:///android_asset/demo_java_js_call.html");

不带参数

        mBtnJavaCallJsWithoutParam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mWebView.loadUrl("javascript:java_call_js_without_param()");
            }
        });

带参数

        mBtnJavaCallJsWithParam.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String param = "'a param from java'";//注意引号
                mWebView.loadUrl("javascript:java_call_js_with_param("
                                + param
                                + ")"
                );
            }
        });

js调用java

  • 设置
        mWebView.addJavascriptInterface(this, "jsbridge");

不带参数

js:
<a onClick="window.jsbridge.callFromJs()">点击这里-->调用java代码,无参数</a><br/>

java:
    @JavascriptInterface
    public void callFromJs() {
        Toast.makeText(this, "callFromJs, 无参", Toast.LENGTH_LONG).show();
    }

带参数

js:
<a onClick="window.jsbridge.callFromJsWithParam('来自js的参数')">点击这里-->调用java代码并传递参数</a><br/>

java:
    @JavascriptInterface
    public void callFromJsWithParam(String param) {
        Toast.makeText(this, "callFromJs, 参数是:" + param, Toast.LENGTH_LONG).show();
    }

其他

  • 完整示例 https://github.com/cheyiliu/JsJavaInteractInAndroid
  • js返回值问题 http://stackoverflow.com/questions/3298597/how-to-get-return-value-from-javascript-in-webview-of-android
  • jsbridge(js桥)开源库推荐 https://github.com/pedant/safe-java-js-webview-bridge

你可能感兴趣的:(JavaScript,java,android,webView)