如何阻止https googlead脚本在webview中运行?

时间:2014-01-26 18:28:17

标签: android webview

我希望阻止脚本在webview中运行,但我找不到解决方案。

在html的头部是我希望阻止的一行代码 -

请注意,该网站是https://,我无法简单地编辑html代码。

非常感谢提前。

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);        

    //run in fullscreen
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    //create a new webview instance and make the current activity as its context
    wb = new WebView(this);

    //show it as our view
    setContentView(wb);

    //enable javascript
    WebSettings webSettings = wb.getSettings();
    webSettings.setJavaScriptEnabled(true); 
    webSettings.setBuiltInZoomControls(true);

    wb.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return false;
        }  

         @Override
            public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {
               if (url.equals("http://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js")) {

                   ByteArrayInputStream test1 = null;
            try {
                test1 = new ByteArrayInputStream("// script blocked".getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                   return new WebResourceResponse("text/javascript", "UTF-8", test1);                                                         


               } else {
                   return super.shouldInterceptRequest(view, url);
               }
            }           
    });             

    //load the website 
    wb.loadUrl("https://example.com/");   
}

1 个答案:

答案 0 :(得分:1)

您可以使用shouldInterceptRequest()来拦截脚本加载。

WebView webview = (WebView) findViewById(R.id.webview);

webview.setWebViewClient(new WebViewClient() {
    @Override
    public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {
       if (url.equals("script_url_to_block")) {
           return new WebResourceResponse("text/javascript", "UTF-8", new ByteArrayInputStream("// script blocked".getBytes("UTF-8")));
       } else {
           return super.shouldInterceptRequest(view, url);
       }
    }
});