shouldOverrideUrlLoading in WebView for Android not running
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.
After some research I conclude that despite what most of the tutorials out there say, shouldOverrideUrlLoading()
does not get called when:
You load a URL like
loadUrl("http://www.google.com");
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
.
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)
.