Android detect webview URL change

2020-01-29 06:42发布

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?

10条回答
Explosion°爆炸
2楼-- · 2020-01-29 07:33

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);
    }
}
查看更多
甜甜的少女心
3楼-- · 2020-01-29 07:34

Try to use onLoadResource. It will be called at least 1 time even if you are using JS to change your url. But it may be called more than one time, so be careful.

查看更多
叼着烟拽天下
4楼-- · 2020-01-29 07:36

I had the same problem. So i've solved this problem by overriding public void onPageStarted(WebView view, String url, Bitmap favicon) method as follows:

 webView.setWebViewClient(new WebViewClient(){

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon)
    {
        // Here you can check your new URL.
        Log.e("URL", url);
        super.onPageStarted(view, url, favicon);
    }

 });

Also you can overridepublic void onPageFinished(WebView view, String url) method to get a new URL at the end of page load process.

查看更多
Lonely孤独者°
5楼-- · 2020-01-29 07:39

This will help to detect redirect caused by javascript.

WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            view.loadUrl("javascript:window.android.onUrlChange(window.location.href);");            }
    };
    myWebView.setWebViewClient(mWebViewClient);
    }
@JavascriptInterface
public void onUrlChange(String url) {
    Toast.makeText(mContext, "Url redirected",Toast.LENGTH_SHORT).show();
}
查看更多
登录 后发表回答