如何在应用履历上的Android WebView中触发JavaScript事件
我的Android应用中有一个WebView,并且每当我需要运行JavaScript函数
I have a WebView in my Android app, and I need to run a JavaScript function whenever
- 已将应用程序/WebView切换到(例如,使用应用程序切换器或点击主屏幕上的图标)
- 设备从睡眠中唤醒(当设备进入睡眠状态时,应用仍在屏幕上)
使用 visibilitychange
我的网页javascript中的事件侦听器仅适用于情况1.
Using a visibilitychange
event listener in my webpage javascript only works for case 1.
理想情况下,我想使用Android onResume()
java函数触发某种javascript事件,但是如何?
Ideally I would like to trigger some kind of javascript event using the Android onResume()
java function, but how?
You can do this using the WebView evaluateJavascript()
method.
首先,您需要在网页javascript中创建一个事件,并添加事件处理程序:
First of all you need to create an event in your webpage javascript, and add the event handler:
window.appResumeEvent = new Event('appresume');
window.addEventListener('appresume', yourFunction, false);
function yourFunction() {…}
设置在全局范围内创建应用恢复事件很重要(可以通过将其设置为 window
的属性来实现).
It's important that you set create the app resume event in global scope (which can be achieved by setting it as a property of the window
).
现在,在您的Android onResume()
方法中,运行 evaluateJavascript()
方法:
Now, in your Android onResume()
method, run the evaluateJavascript()
method:
@Override
protected void onResume() {
super.onResume();
mainWebView.evaluateJavascript("(function() { window.dispatchEvent(appResumeEvent); })();", new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
}
});
}
请注意,javascript必须包装在立即调用的函数表达式中.另请注意, dispatchEvent()
将事件变量作为参数,而不是事件名称字符串.
Note the javascript has to be wrapped in an immediately-invoked function expression. Also note dispatchEvent()
takes the event variable as the argument, not the event name string.
更多信息:在javascript中创建和调度事件(MDN)
对于我的完整 MainActivity.java
,请单击show snippet:
For my full MainActivity.java
click show snippet:
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView mainWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainWebView = findViewById(R.id.activity_main_webview);
mainWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = mainWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mainWebView.loadUrl("file:///android_asset/www/index.html");
}
@Override
protected void onResume() {
super.onResume();
mainWebView.evaluateJavascript("(function() { window.dispatchEvent(appResumeEvent); })();", new ValueCallback<String>() {
@Override
public void onReceiveValue(String value) {
}
});
}
}