views:

395

answers:

2
private class HelloWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }   }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        webview = (WebView) findViewById(R.id.webview);
        webview.setWebViewClient(new HelloWebViewClient());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl("http://mydomain.com");
    }

This is a very simple webview demo ( I followed a tutorial to write it). When a user loads up my application, this webview pops up and he's able to go on the internet inside it.

How do I "listen" for an event?

  • When a URL contains "google.com"
  • Or, when the HTML contains the word "google"

As the user is using my webview to browse the web, I'd like to listen to those things and then call a function when it happens.

A: 

There are a view methods which seems like good candidates. You really should have a look at the doc for the class here.

public void onLoadResource (WebView view, String url)

Should let you inspect the url before the page is loaded.

public void onPageFinished (WebView view, String url)

Should let you search the actual finished loaded content.

willcodejavaforfood
A: 

To listen for google.com requests you should override shouldOverrideUrlLoading like in your code sample, but you need to provide an alternative action for those request like in the below code snippet.

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url.contains("google.com")) {
        // Here you can do whatever you want
        view.loadUrl("http://example.com/");
        return true;
    }

    // The default action, open the URL in the same WebView
    view.loadUrl(url);
    return true;
}
gabrielf