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?
Asked
Active
Viewed 3,318 times
4
-
Use JavascriptInterface of webview and window hashChange event in javascript – mitvenkatesan Oct 30 '14 at 12:19
2 Answers
11
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.

solo_assassin
- 483
- 4
- 20
-
2
-
This is excellent, it will detect the url change. But can you suggest how to navigate to the pages in SPA without reloading the page. I am searching, but couldn't get any hint. Thanks – Ranjit Singh Shekhawat Sep 17 '20 at 08:39
-
I believe you want to have path routing instead of hash routing without the page reload. In that case you can use history api. https://developer.mozilla.org/en-US/docs/Web/API/History – solo_assassin Sep 17 '20 at 08:49
0
As mitvenkatesan described in his comment to the question, this can be achieved by overriding the window.onhashchange() event of the page inside the WebView.
It turns out that this solution has already been addressed in another question.