Reputation: 846
I have a WebView
within an app that loads a specific url, it's possible however that when using the app the user may be taken/redirected within the web view to another url, for example www.cheese.com, that shouldn't be viewed within the app.
Is it possible to listen for that url (www.cheese.com) within the WebView
and if it begins to load redirect it to another url before it finishes loading?
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
mWebView.loadUrl("https://example.com");
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
}
Upvotes: 0
Views: 766
Reputation: 149
// Load CustomWebviewClient in webview and override shouldOverrideUrlLoading method
mWebView.setWebViewClient(CustomWebViewClient)
class CustomWebViewClient extends WebViewClient {
@SuppressWarnings("deprecation")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
final Uri uri = Uri.parse(url);
return handleUri(uri);
}
@TargetApi(Build.VERSION_CODES.N)
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
final Uri uri = request.getUrl();
return handleUri(uri);
}
private boolean handleUri(final Uri uri) {
Log.i(TAG, "Uri =" + uri);
final String host = uri.getHost();
final String scheme = uri.getScheme();
// Based on some condition you need to determine if you are going to load the url
// in your web view itself or in a browser.
// You can use `host` or `scheme` or any part of the `uri` to decide.
/* here you can check for that condition for www.cheese.com */
if (/* any condition */) {
// Returning false means that you are going to load this url in the webView itself
return false;
} else {
// Returning true means that you need to handle what to do with the url
// e.g. open web page in a Browser
final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
return true;
}
}
}
Upvotes: 1
Reputation: 6761
Try to use something like this:
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null && url.startsWith("http://www.cheese.com")) {
//do what you want here
return true;
} else {
return false;
}
}
});
Upvotes: 0