JS与IOS、Android的交互

一、JS与Android

放在了assets文件夹下了(注意若使用的是AS这个IDE,assets文件夹应放在src/main目录下)

<!DOCTYPE html>
<html>

   <head>
      <meta charset="utf-8">
      <title>葛夫锋</title>
      
      <script>
         function callAndroid(){
            test.hello("js调用了android中的hello方法");
         }
      </script>
   </head>

   <body>
      <button type="button" id="button1" onclick="callAndroid()">js调用android中的代码</button>
   </body>

</html>

代码非常简单,页面中就一个按钮,点击这个按钮调用callAndroid函数,这里需注意callAndroid函数中的语句是android中对外的的一个函数,在android中的代码:

{
    ...   
    webSettings.setJavaScriptEnabled(true);
    webView.addJavascriptInterface(this, "test");//对应js中的test.xxx
    webView.loadUrl("file:///android_asset/js_web.html");
}
@JavascriptInterface
public void hello(String msg){//对应js中xxx.hello("")
    Log.e("webview","hello");
    Toast.makeText(this,msg,Toast.LENGTH_LONG).show();
}

这里需注意的是hello函数加上注解@javascriptInterface,这样点击html中的按钮就会调用android中的hello方法了。

二、Android调用JS代码

js代码如下:

<script>
   function callJS(){
      alert("android调用了js中的callJS方法");
   }
</script>

android代码如下:

public void click(View view){
    webView.post(new Runnable() {
        @Override
        public void run() {
            webView.loadUrl("javascript:callJS()");
        }
    });
}

当android中的按钮被点击时会触发click方法,然后执行webview.loadUrl("javascript:callJS()"),然后js中正好有callJS这个方法,然后alert()就会被执行。

这个总结很好:

https://github.com/shaojiankui/iOS-WebView-JavaScript

posted @ 2017-07-07 18:26  Shoestrong  阅读(2001)  评论(1编辑  收藏  举报
更多精彩请访问个人主页http://shoestrong.cc