问题
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