首页 > 代码库 > JS和Android交互

JS和Android交互

 

 

    
     //本地webview写法
    webview = (WebView) findViewById(R.id.webview); webview.loadUrl("http://192.168.1.103/index.html"); webview.getSettings().setJavaScriptEnabled(true); //允许js脚本运行 webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); webview.getSettings().setBuiltInZoomControls(true); webview.getSettings().setJavaScriptEnabled(true); webview.addJavascriptInterface(new JsToJava(mContext),"mObject");//添加映射对象到js

 

js代码


body> <a>js中调用本地方法</a> <script> function funFromjs(){ document.getElementById("helloweb").innerHTML="HelloWebView,i‘m from js"; } var aTag = document.getElementsByTagName(‘a‘)[0]; aTag.addEventListener(‘click‘, function(){ //调用android本地方法 myObj.fun1FromAndroid("调用android本地方法fun1FromAndroid(String name)!!"); return false; }, false); </script> <p></p> <div id="helloweb"> </div> </body> </html>

本地和js映射的对象:

public class JavaScriptObject {
    Context mContxt;

    public JavaScriptObject(Context mContxt) {
        this.mContxt = mContxt;
    }

    public void fun1FromAndroid(String name) {
        Toast.makeText(mContxt, name, Toast.LENGTH_LONG).show();
    }

    public void fun2(String name) {
        Toast.makeText(mContxt, "调用fun2:" + name, Toast.LENGTH_SHORT).show();
    }
}

 

JS和Android交互