javascript - How to monitor url hash changes in Android webview
ringa_lee
ringa_lee 2017-06-12 09:25:05
0
1
1898

Scenes

Loading a SPA (Single Page Application) website in Android's webview

process

I use the shouldoverrideurl method to monitor the URL of Webview and perform some preprocessing on the URL

However, most of the changes in SPA are hash value changes, so this method cannot monitor changes

Example

Jump from a.html#/home to a.html#/other

question

Is there any way to monitor changes in hash values?

ringa_lee
ringa_lee

ringa_lee

reply all(1)
学习ing

Only available through HTML5’s newly added window.onhashchange() API. shouldoverrideurl should not be monitored.

If you don’t want to modify the js code, you can inject it in java:

Define a class that handles js:

private class MyJSI {
    public void doStuff() {
        // 你的逻辑
    }
}

Inject into webview:

webView.addJavascriptInterface(new MyJSI(), "myjsi");

Listen to onhashchange event:

webview.setWebViewClient(new WebViewClient() {  

    public void onPageFinished(WebView view, String url) {
        view.loadUrl("javascript:window.onhashchange = function() { myjsi.doStuff(); };");
    }
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template