shouldOverrideUrlLoading in WebView for Android not running

那年仲夏 提交于 2019-11-27 07:00:27

After some research I conclude that despite what most of the tutorials out there say, shouldOverrideUrlLoading() does not get called when:

  1. You load a URL like

    loadUrl("http://www.google.com");
    
  2. The browser redirects the user automatically via an HTTP Redirect. (See the comment from @hmac below regarding redirects)

It does however, get called when you you click on a link inside a webpage inside the webview. IIRC the twitter authorization uses an HTTP Redirect.. Bummer, this would be helpful if it worked how all the tutorials say it does. I think this is from a very old version the Android API...

You might want to consider overriding the onProgressChanged method of a WebChromeClient like here: How to listen for a WebView finishing loading a URL? or the onPageFinished() method of the WebViewClient.

Maks

I've found what I think is a reasonable way to do this thanks to the previous answer and comments pointing me in the right direction.

What I did is override onPageStarted and onPageFinished in a custom WebViewClient. The code goes something like this...

@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
  if (pendingUrl == null) {
    pendingUrl = url;
  }
}

@Override
public void onPageFinished(WebView view, String url) {
  if (!url.equals(pendingUrl)) {
    Log.d(TAG, "Detected HTTP redirect " + pendingUrl + "->" + url);
    pendingUrl = null;
  }
}

And of course along with the Log.d you would put any specific code you want to run upon detecting the redirect.

metodieva

For people stumbling across this, when the method shouldOverrideUrlLoading(WebView view, WebResourceRequest request) is not being called, look up your minSdkVersion. If you use below API 24 you should use shouldOverrideUrlLoading(WebView view, String url).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!