Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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?

like image 752
user2127011 Avatar asked Mar 02 '13 16:03

user2127011


1 Answers

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.

like image 54
thomas.winckell Avatar answered Oct 10 '22 22:10

thomas.winckell