Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen for URL fragment id change in WebView

It seems that the WebViewClient methods such as shouldInterceptRequest(), onPageStarted(), and shouldOverrideUrlLoading() only listen for URL changes that cause the WebView to load a new page. Is there a way to detect URL changes for fragment IDs, i.e. index.html#fragment_id, on a WebView?

like image 658
jpetitto Avatar asked Dec 20 '22 10:12

jpetitto


1 Answers

I know that this is a really old question but i found out a solution that isn't available anywhere in Stack Overflow. jpetitto's answer works but it messes up javascript if we use hash change for routing or other such features.

I found out that by overriding the method doUpdateVisitedHistory in WebViewClient we can catch url's on hash change. Do see below snippet for example.

mWebView.setWebViewClient(new WebViewClient() {

        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            super.doUpdateVisitedHistory(view, url, isReload);
            // somecode to run on hash change.
        }

}

Note: this method is fired on hash change and url change.

like image 128
Srin Avatar answered Dec 31 '22 12:12

Srin