Android webview 与JS交互

mWebView.getSettings().setBuiltInZoomControls(true);//缩放
mWebView.getSettings().setJavaScriptEnabled(true);//添加对JavaScript支持

 

mWebView.addJavascriptInterface(new Object() {
            
            /**
             * 对于JS调用的方法必须声明  @JavascriptInterface
             * 否则,对于4.4以及以上的版本,无法被执行
             *
             */
            @JavascriptInterface
            public void getInfo(String _title, String _articleType) {
                /**
                 * -------------------------------------
                 *
                 *
                 * 这样确实能够获取到JavaScript中传入的数据
                 *
                 *
                 * -------------------------------------
                 */
                Toast.makeText(WebViewDemo3.this,
                        "_title:" + _title + "\n_articleType:" + _articleType, Toast.LENGTH_SHORT)
                        .show();
                Log.w("jk", "_title:" + _title + "\n_articleType:" + _articleType);
            }
        }, "tlsj");

//------------------------------------

<html>
    <head>
      <title>JS交互</title>
      <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
      <script type="text/javascript">
        function invokedByJava(param) {
            document.getElementById("content").innerHTML = "Java has invoked JS function and returnd the data:"+param;
        }
        function todata(){
            var title = 'HTML Title';
            var articleType = 'HTML Content';
            window.tlsj.getInfo(title,articleType);//----调用Java代码中声明的对象方法,传递相关参数
        }
        function tojava(){
            window.stub.jsMethod('来至JS的参数');
        }
      </script>
    </head>
    <body onload="todata()">
      <p id="content"></p>
      <p>
          <input type="button" value="调用Java方法" onclick="tojava()" />
          <input type="button" value="调用alert" onclick="alert('hello')" />
      </p>
    </body>
</html>

 

posted @ 2015-10-10 09:54  Meiling  阅读(186)  评论(0)    收藏  举报