我在加载特定网址的应用中有一个WebView
,但是在使用该应用时,可能会在网络视图中将用户/重定向到另一个网址,例如www.cheese.com ,不应该在应用程序中查看。
是否可以在WebView
内收听该网址(www.cheese.com),如果它在加载完成之前开始加载重定向到另一个网址?
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
mWebView.loadUrl("https://example.com");
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
}
答案 0 :(得分:1)
// 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;
}
}
}
答案 1 :(得分:0)
尝试使用以下内容:
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;
}
}
});