Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to intercept url loads in WebView (android)?

I have a WebView in which I load a page with a custom link (like app://action). I registered the url schemes in the manifest file and when I click on the link, the onResume() method of my Activity is called with the correct data and it works OK.

My problem is that the WebView still try to load the link and my WebView ends up to show a "Web page unavailable" message. I don't want that.

How can I prevent the WebView to load the url?

Here's my code :

WebView banner = ...
banner.setWebViewClient(new WebViewClient() {

    @Override
    public void onLoadResource(WebView view, String url) {

        if (url.startsWith("app://")) {

            Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url), getContext(), Main.class);
            //startActivity(i);
        }
    }
}

banner.loadUrl("url_to_the_banner");
like image 424
Alexis Avatar asked Dec 07 '12 09:12

Alexis


People also ask

How do I stop a WebView from loading a URL?

You have to override the method shouldOverrideUrlLoading (see here) of your WebViewClient , rather than the one you are overriding. Just return false if you want to load the page; true if you want to block loading.

What is a WebView URL?

The WebView class is an extension of Android's View class that allows you to display web pages as a part of your activity layout. It does not include any features of a fully developed web browser, such as navigation controls or an address bar. All that WebView does, by default, is show a web page.


2 Answers

Use WebViewClient.shouldOverrideUrlLoading instead.

public boolean shouldOverrideUrlLoading(WebView view, String url){
    // handle by yourself
    return true; 
}

WebViewClient Reference

Updates: Method shouldOverrideUrlLoading(WebView, String) is deprecated in API level 24. Use shouldOverrideUrlLoading(WebView, WebResourceRequest) instead.

like image 63
faylon Avatar answered Sep 28 '22 13:09

faylon


But it must return false otherwise, so:

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
    if(url.startsWith(myString){
        // handle by yourself
        return true;
    } 
    // ...
    return false;
}
like image 39
ldd Avatar answered Sep 28 '22 12:09

ldd