It is time for another WebView example. This time on how you can intercept any attempts at loading a web page and redirect the user to a different URL instead.
This can be achieved simply by registering a WebViewClient which overrides the shouldOverrideUrlLoading() method in which you tell the WebView to load a different URL from the one the user had requested.
The example below loads lexandera.com first, but when the user clicks any link on the page, he is redirected to yahoo.com:
WebView browser = (WebView)findViewById(R.id.browser);
browser.setWebViewClient(new WebViewClient() {
/* On Android 1.1 shouldOverrideUrlLoading() will be called every time the user clicks a link,
* but on Android 1.5 it will be called for every page load, even if it was caused by calling loadUrl()! */
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
/* intercept all page load attempts and load yahoo.com instead */
String myAlternativeURL = "http://yahoo.com";
if (!url.equals(myAlternativeURL)) {
view.loadUrl(myAlternativeURL);
return true;
}
return false;
}
});
browser.loadUrl("http://lexandera.com/");
Please note that calling loadUrl() does not trigger the shouldOverrideUrlLoading() method, which means that we do not need to worry about endless recursion when calling loadUrl() from within shouldOverrideUrlLoading()!
UPDATE: The above statement is no longer true for Android 1.5! Calling loadUrl() will now also trigger the shouldOverrideUrlLoading() method! This means that you need to make sure that you are not creating an infinite loop when calling loadUrl() from shouldOverrideUrlLoading()!
Related posts:
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=ed91eca5-2c5e-4b86-8b88-8af5a1b703f7)

[...] lexanderA: Intercepting page loads in WebView [...]
didnt work for me :(
shouldOverrideUrlLoading() will be called every time the user clicks a link
and not everytime the webview load an url
didnot work for me either.
an infinite loop occurred
I have tested the code again and it appears that Android 1.5 behaves differently from Android 1.1 on which the example was based: shouldOverrideUrlLoading() wasn’t triggered by loadUrl() in 1.1, but it is triggered by it in 1.5, which does indeed cause an infinite loop. I’ll try to update the example as soon as possible. Thanks for the report.