How to add window message event Listener - Android WebView

≡放荡痞女 提交于 2020-07-09 12:42:48

问题


How to add an event listener to handle window message event in a WebView. I have tried this,

webView.evaluateJavascript("window.addEventListener('message', function (e) { Android.logData('HELLO')});", null);

But it is not working. Is there any way to achieve this?


回答1:


After exploring I didn't find any way to get data from the website running in WebView to the app without adding any code to in the website. And finally, I decided to make the necessary changes on my website as well. And this is how I did it:

In App

Created a class

private class JsObject {
    @JavascriptInterface
    public void shareData(String data) {
        Log.v(LOG_TAG, data);
    }
}

Add an instance of the new class as Javascript Interface to the WebView with a name

ssWebView.addJavascriptInterface(new JsObject(), "Android");

This instance will be added to the window object of the WebView as Android(name, the second argument of the above function)

In Website

In the website to share data

window.Android && window.Android.shareData("This is the data from website");


来源:https://stackoverflow.com/questions/59927835/how-to-add-window-message-event-listener-android-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!