问题
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.
回答1:
The documentation of shouldOverrideUrlLoading took me a couple readings to understand.
If you want the current WebView to handle the url then there is no need to call WebView.loadUrl, just return false. If you want your app to do something completely different with particular URLs then do what you need and return true.
I wanted all URLs that were not from my host to be handled by the phone's browser app rather than my WebView. Here is my implementation:
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean returnVal = false;
if(url.startsWith(mUrlHost)) {
//current Webview handles the URL
} else {
Toast.makeText(mActivity, "Launching Browser", Toast.LENGTH_SHORT).show();
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
mActivity.startActivity(intent);
returnVal = true;
}
return returnVal;
}
回答2:
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.
回答3:
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;
}
来源:https://stackoverflow.com/questions/2219556/how-do-i-listen-for-something-in-webview-android