27

I have written a simple helloworld app with a WebView which has a link to CNN on a simple.html page in my asset folder.

<a href="http://cnn.com">cnn.com</a>

How can I capture the click on this on my Activity, stop the WebView from navigating, and then inform the Activity that "http://CNN.com" was clicked?

RominaV
  • 3,335
  • 1
  • 29
  • 59
Ian Vink
  • 66,960
  • 104
  • 341
  • 555

1 Answers1

72

Then you have to set a WebViewClient to your WebView and override shouldOverrideUrlLoading and onLoadResource methods. Let me give you a simple example:

WebView yourWebView; // initialize it as always...
// this is the funny part:
yourWebView.setWebViewClient(yourWebClient);

// somewhere on your code...
WebViewClient yourWebClient = new WebViewClient(){
    // you tell the webclient you want to catch when a url is about to load
    @Override
    public boolean shouldOverrideUrlLoading(WebView  view, String  url){
        return true;
    }
    // here you execute an action when the URL you want is about to load
    @Override
    public void onLoadResource(WebView  view, String  url){
        if( url.equals("http://cnn.com") ){
            // do whatever you want
        }
    }
}
Cristian
  • 198,401
  • 62
  • 356
  • 264
  • Sorry I know this is stale but it was exactly what I was looking for EXCEPT....my navigation doesn't complete. When the user clicks a link in the WebView it goes to shouldOverrideLoading and does it's thing but doesn't complete the navigation. I do want it to complete just want to sniff what they selected first. – GPGVM May 04 '12 at 18:01
  • 1
    In that case you should not return true in the shouldOverrideUrlLoading – Cristian May 04 '12 at 18:14
  • 1
    so return false then unless you really want to abort. – GPGVM May 04 '12 at 18:17
  • Is there a way to differentiate between resources requested (like CSS, JS files, images) and user-clicked links? Please take a look at [my question](https://stackoverflow.com/questions/40922547/stop-android-webview-from-trying-to-load-capture-resources-like-css-on-loaddata) – HelpingHand Dec 02 '16 at 02:20