如何添加窗口消息事件监听器-Android WebView [英] How to add window message event Listener - Android WebView
问题描述
如何添加事件侦听器以处理WebView
中的window
消息事件.我已经尝试过了,
webView.evaluateJavascript("window.addEventListener('message', function (e) { Android.logData('HELLO')});", null);
但是它不起作用.有什么办法可以做到这一点?
探索之后,我发现没有任何方法可以将运行在WebView
中的网站的数据获取到应用程序,而无需在网站中添加任何代码.最后,我决定也要在我的网站上进行必要的更改.这就是我的方法:
在应用中
创建了一个课程
private class JsObject {
@JavascriptInterface
public void shareData(String data) {
Log.v(LOG_TAG, data);
}
}
将新类的实例作为Javascript接口添加到名称为
private class JsObject {
@JavascriptInterface
public void shareData(String data) {
Log.v(LOG_TAG, data);
}
}
的WebView
ssWebView.addJavascriptInterface(new JsObject(), "Android");
此实例将作为Android
(名称,上述函数的第二个参数)添加到WebView
的window
对象中
在网站上
在网站上共享数据
window.Android && window.Android.shareData("This is the data from website");
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?
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");
这篇关于如何添加窗口消息事件监听器-Android WebView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!