Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android detect webview URL change

I have a webview in my android app and would like to detect when the url changes.

I want to use this to hide the info button in the top bar when the user is on the info.php page and show it again when he is not on the info.php page.

I googled but can't find any working code, can anybody help me?

like image 468
Daniel Avatar asked Feb 16 '12 13:02

Daniel


3 Answers

I know I'm late to the game but I ran into this issue over and over ... I finally found a sloution which is pretty straight forward. Just override WebViewClient.doUpdateVisitedHistory

override fun doUpdateVisitedHistory(view: WebView?, url: String?, isReload: Boolean) {
    // your code here
    super.doUpdateVisitedHistory(view, url, isReload)
}

It works with all url changes even the javascript ones!

If this does not make you happy then I don't know what will :)

like image 113
grAPPfruit Avatar answered Nov 03 '22 23:11

grAPPfruit


You can use WebViewClient.shouldOverrideUrlLoading to detect every URL changes on your WebViewClient

like image 43
RPB Avatar answered Nov 04 '22 00:11

RPB


For those load url by javascript. There is a way to detect the url change by JavascriptInterface. Here I use youtube for example. Use JavaScriptInteface has async issue, luckily its just a callback here so that would be less issue. Notice that @javascriptinterface annotation must be existed.

{
    youtubeView.getSettings().setJavaScriptEnabled(true);
    youtubeView.setWebViewClient(mWebViewClient);
    youtubeView.addJavascriptInterface(new MyJavaScriptInterface(),
            "android");
    youtubeView.loadUrl("http://www.youtube.com");

}

WebViewClient mWebViewClient = new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        view.loadUrl("javascript:window.android.onUrlChange(window.location.href);");
    };
};

class MyJavaScriptInterface {
    @JavascriptInterface
    public void onUrlChange(String url) {
        Log.d("hydrated", "onUrlChange" + url);
    }
}
like image 14
Shu Zhang Avatar answered Nov 03 '22 23:11

Shu Zhang