Listen for URL fragment id change in WebView

房东的猫 提交于 2019-12-23 14:52:13

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/26555616/listen-for-url-fragment-id-change-in-webview

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