Android communicate with JS

Android calls Js

  • loadUrl()

Js method calls the method by loadUrl WebView ().

mWebView.loadUrl("javascript:callJsDefault()");

 //在android调用js有参的函数的时候参数要加单引号
String param = "\'来自Android的参数\'";
mWebView.loadUrl(String.format("javascript:callJsWithParams(%s)", param));
  • evaluateJavascript()

Js method calls the method evaluateJavascript WebView (), returns the value of this method can be obtained Js method is performed.

mWebView.evaluateJavascript("javascript:callJsWithReturn(2,3)",
value -> Toast.makeText(MainActivity.this, "Js的计算结果为:" + value, Toast.LENGTH_SHORT).show());

Js call Android

  • addJavascriptInterface()

Creating a class through the WebView addJavascriptInterface () method available to use Js, Js call the method by which we write in Android.

public class JsCallAndroid {

    private Context mContext;
    public JsCallAndroid(Context context) {
        mContext = context;
    }
    
    //供Js调用的方法要加JavascriptInterface注解
    @JavascriptInterface
    public void hello(String msg){
        Toast.makeText(mContext,msg,Toast.LENGTH_SHORT).show();
    }
    
    /*...*/
}
//"android"为Js中调用对象的名称
mWebView.addJavascriptInterface(new JsCallAndroid(this), "android");

Js call

function callAndroid(){
        // 由于对象映射,所以调用android对象等于调用Android映射的对象
            android.hello("js调用了android中的hello方法!!!");
        }
  • alert()、confirm()、prompt()

By rewriting the WebChromeClient onJsAlert (), onJsConfirm (), onJsPrompt () method of response Js alert (), confirm (), prompt () call.

mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Alert")
                        .setMessage(message)
                        .setPositiveButton(android.R.string.ok, (dialog, which) -> result.confirm())
                        .setNegativeButton(android.R.string.cancel, (dialog, which) -> result.cancel())
                        .setCancelable(false)
                        .create()
                        .show();
                return true;
            }

        });

Js Code

function callAndroidAlert(){
            alert("来自Js的提示");
        }
  • shouldOverrideUrlLoading

Js Android defined with a special set of URL, and then rewriting shouldOverrideUrlLoading WebViewClient () method, intercepting url, url contains parsed data, do different actions for different data.

mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains("protocol://webview?")) {
                    Map<String, String> dataMap = getUrlDataMap(url);
                    if (dataMap != null) {
                        switch (dataMap.get("operate")) {
                            case "toast":
                                Toast.makeText(MainActivity.this, dataMap.get("msg"), Toast.LENGTH_LONG).show();
                                break;
                            case "startActivity":
                                /*...*/
                                break;
                            default:
                                break;
                        }
                    }
                } else
                    view.loadUrl(url);
                return true;
            }
        });

    /**
     * 获取URl所包含的数据
     * @param url
     * @return 数据的map集合
     */
    private Map<String, String> getUrlDataMap(String url) {
        Map<String, String> map = null;
        try {
            url = URLDecoder.decode(url, "utf-8");
            String substring = url.substring(url.indexOf("?") + 1);
            String[] split = substring.split("&");
            map = new HashMap<>();
            String[] entry;
            for (String s : split) {
                entry = s.split("=");
                map.put(entry[0], entry[1]);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return map;
    }

Js Code

//这里用一个a标签做示例
<a href="protocol://webview?operate=toast&msg=Js通过url控制Android执行方法">通过url执行方法</a>

Expansion mode

Js and Android interactions can also be done by JsBridge, JsBridge is an open source third-party library, its role and name, can communicate as a bridge between Js and Android. Use are introduced on Github, the Internet has a lot of blog, are interested in their own search, I do not write.

The exemplary codes Html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
<p id="content"></p>
<p><button type="button" id="button1" οnclick="callAndroid()">点击按钮则调用callAndroid函数</button></p>
<a href="protocol://webview?operate=toast&msg=Js通过url控制Android执行方法">通过url执行方法</a>
<script type="text/javascript">

        var content = document.getElementById("content");

        function callAndroid(){
        // 由于对象映射,所以调用android对象等于调用Android映射的对象
            android.hello("js调用了android中的hello方法!!!");
        }

        function callAndroidAlert(){
            alert("来自Js的提示");
        }

         // Android需要调用的方法
         function callJsDefault(){
            content.innerHTML='Android调用了Js的默认方法';
         }

         function callJsWithParams(params){
            content.innerHTML = "Android调用了Js的带参方法:" + params;
         }

         function callJsWithReturn(a,b){
            return a+b;
         }

    </script>
</body>
</html>

to sum up

All of the above Js and interaction methods for Android, each have their own characteristics, which method Js call in Android, using interception Url way more, given the versatility to take care of ios, interception Url two side implementation costs one of the least, if you do not consider ios end, which can be so casual.

Published 57 original articles · won praise 26 · views 40000 +

Guess you like

Origin blog.csdn.net/Ever69/article/details/104518055