user2127011
user2127011

Reputation: 91

Android WebView: Is it possible to detect URL hash change?

I need to detect URL hash changes in an Android WebView but can't find any way to do so. shouldOverrideUrlLoading() fires on the initial page load, but does not fire for any subsequent hash changes once the page has loaded.

Is this even possible with the Android WebView?

Upvotes: 9

Views: 8306

Answers (1)

thomas.winckell
thomas.winckell

Reputation: 1277

It is possible.

You have to declare a Javascript Interface like this :

private class MyJSI {
         public void doStuff()
         {
         }
}

And link your webview with the Javascript Interface like this :

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

Then, you have to write some javascript code when the page is loaded, to call the function doStuff on hash change.

webview.setWebViewClient(new WebViewClient() {  

         public void onPageFinished(WebView view, String url)  
         {
                 view.loadUrl("javascript:window.onhashchange = function() { myjsi.doStuff(); };");
         }
});

I hope it helps. I have tested it, and it works.

Upvotes: 11

Related Questions