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

后端 未结 4 1378
小鲜肉
小鲜肉 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

    Recently we had to develop a project that needed to communicate our native Android app with an external webview integration from a third party.

    The idea that this question raises in stackoverflow is very interesting, more so if you can't touch the JS code of that webview.

    I describe what we did to be able to communicate the webview with the native app through the message steps via the JS PostMessage API.

    Using our webview implementation. We implemented the onPageFinished method in order to inject our JS code to load the web.

    override fun onPageFinished(url: String?) {
    webview.loadUrl(
    "javascript:(function() {" +
        "window.parent.addEventListener ('message', function(event) {" +
        " Android.receiveMessage(JSON.stringify(event.data));});" +
        "})()"
    )
    }
    

    Basically what we are doing is creating a listener that sends those messages to our own JS and Android Bridge interface. Which we've previously created in the webview setup in our Android activity as we normally do with addJavascriptInterface

    webview.addJavascriptInterface(JsObject(presenter), "Android”)
    

    This way, we already have that communication bridge and all the messages sent by the postMessage will reach us in that interface that is subscribed with that listener.

    class JsObject(val presenter: Presenter) {
        @JavascriptInterface
        fun receiveMessage(data: String): Boolean {
            presenter.onDataReceived(data)
            Log.d("Data from JS", data)
            return true
        }
    

提交回复
热议问题