Android detect webview URL change

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 :)


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


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);
    }
}