公共类 WebViewActivity 扩展 AppCompatActivity {
WebView webview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
webview = new WebView(this);
webview.setWebViewClient(new MyWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
setContentView(webview);
}
private class MyWebViewClient extends WebViewClient {
public boolean shouldOverrideKeyEvent (WebView view, KeyEvent event) {
return true;
}
public boolean shouldOverrideUrlLoading (WebView view, String url) {
if (Uri.parse(url).getHost().equals("http://stackoverflow.com")) {
return false;
}
return true;
}
}
我想屏蔽
WebView
中的某个网址,如何屏蔽该网址?此代码不起作用。
如果您想要根据 文档执行特定行为,则应该返回 true。
如果主机应用程序想要离开当前应用程序,则返回 true WebView 并自行处理 url,否则返回 false。
阻止所有网址工作解决方案,即使我尝试过。
public class MainActivity extends Activity {
private WebView wv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
wv1 = new WebView(this);
setContentView(wv1);
wv1.getSettings().setLoadsImagesAutomatically(true);
wv1.getSettings().setJavaScriptEnabled(true);
wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv1.loadUrl("http://www.kart.epizy.com");
wv1.setWebViewClient(new MyWebViewClient());
wv1.setClickable(true);
}
public class MyWebViewClient extends WebViewClient {
public boolean shuldOverrideKeyEvent(WebView view, KeyEvent event) {
// Do something with the event here
return true;
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//return false to allow urls or add your condition like
//return url.equals("https://play.google.com/store/apps/developer?id=kArt+Developers");
return true;
}
} }
你可以这样做:
public boolean shouldOverrideUrlLoading (WebView view, String url) {
if (Uri.parse(url).getHost().equals("http://stackoverflow.com")) {
view.stopLoading();
return false;
}
return true;
}
当你在shouldOverrideUrlLoading覆盖方法中拦截请求并检测到要阻止的URL时,stopLoading将停止加载网站,并且你将在此URL上得到阻止, 现在您正在检测 URL,但无法管理它们