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

转载于:https://www.cnblogs.com/shoestrong/p/7133642.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值