How to fire javascript event in Android WebView on app resume

你。 提交于 2021-02-10 13:15:15

问题


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?


回答1:


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

            }
        });
    }
}


来源:https://stackoverflow.com/questions/52452246/how-to-fire-javascript-event-in-android-webview-on-app-resume

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!