简体   繁体   中英

How to fire javascript event in Android WebView on app resume

I have a WebView in my Android app, and I need to run a JavaScript function whenever

  1. the app/WebView is switched to (eg using the app switcher or tapping the icon from the home screen)
  2. the device wakes from sleep (with the app having still been on the screen when the device went to sleep).

Using a visibilitychange event listener in my webpage javascript only works for case 1.

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.

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() {…}

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 ).

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) {

        }
    });
}

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.

More info: Creating and dispatching events in javascript (MDN)

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) { } }); } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM