• 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

  • 相关阅读:
    向局域网共享文件夹 写文件(示例)
    安装adb之后出现 找不到设备的情况
    .net 下发送calendar
    解决api 跨域 webconfig添加节点
    String类为什么是不可变的
    Sql
    2020职业规划
    摘录
    Docker
    软件测试工程师的职责是什么
  • 原文地址:https://www.cnblogs.com/shoestrong/p/7133642.html
Copyright © 2020-2023  润新知