Can the PostMessage API be used to communicate with an Android WebView?

后端 未结 4 1380
小鲜肉
小鲜肉 2021-02-03 23:43

I usually use the HTML5 PostMessage API to communicate information from my iframed content to the parent frame. Recently I\'ve had my content used inside an Android WebView (as

4条回答
  •  醉话见心
    2021-02-04 00:15

    I was facing similar issue, I wanted to listen to .postMessage event occuring in webview. I checked in raw html that the event was fired like this

    window.parent.postMessage(JSON.stringify(message), '*');

    Hence I dug more into postMessage and found this link for adding eventListener

    window.addEventListener("message", receiveMessage, false);
    
    function receiveMessage(event)
    {
      if (event.origin !== "http://example.org:8080")
        return;
    
      // ...
    }
    

    durban's answer helped me for setting up Android JS Interface.

    Firstly a custom class for JavascriptInterface like this

    class JsObject {
        @JavascriptInterface
        public void receiveMessage(String data) {
            Log.i("JsObject", "postMessage data="+data);
            //handle data here
        }
    }
    

    Add javascriptInterface to webview before loading url/html

    webView.addJavascriptInterface(new JsObject(), "Android"); //"Android" is just a name
    

    Then call javascript in the onPageStarted callback of WebViewClient like below

      @Override
      public void onPageStarted(WebView view, String url, Bitmap favicon) {
            webView.loadUrl("javascript:(function() {" +
                                "function receiveMessage(event) {\n" +
                                "Android.receiveMessage(JSON.stringify(event.data));\n" +
                                "}" +
                                "window.addEventListener(\"message\", receiveMessage, false);"+
                                "})()"
            );
            Log.i(TAG, "onPageStarted "+url);
      }
    

提交回复
热议问题