search

Home  >  Q&A  >  body text

javascript - How to monitor url hash changes in Android webview

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_leeringa_lee2748 days ago1880

reply all(1)I'll reply

  • 学习ing

    学习ing2017-06-12 09:27:05

    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(); };");
        }
    });
    

    reply
    0
  • Cancelreply