How to fire javascript event in Android WebView on app resume
Asked Answered
K

1

9

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

  1. the app/WebView is switched to (e.g. 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?

Keir answered 21/9, 2018 at 23:47 Comment(0)
K
7

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

            }
        });
    }
}
Keir answered 22/9, 2018 at 0:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.