如何在WebView中阻止URL?

时间:2018-03-10 06:36:22

标签: android url block

公共类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中的网址,如何屏蔽网址?此代码不起作用。

2 个答案:

答案 0 :(得分:0)

如果您需要根据documentation的特定行为,则应返回true。

  

如果主机应用程序想要保留当前值,则返回true   WebView并处理url本身,否则返回false。

答案 1 :(得分:0)

阻止所有网址工作解决方案,即使我尝试过它。

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;
    }
} }