简体   繁体   中英

How to block a particular resource from loading in webview

I've searched a lot for this but did not find any answers. I am developing an android app in which at some point, a webview is displayed which shows you a webpage. But I am really worried about a small advertisement on the web view which shows porn content. Is there any way I can block that from loading on the webpage? Every resource passes the onLoadingRecource() method...Is this the place where i can find a solution? I really need help. Thank you.

Since API 11, there's WebViewClient.shouldInterceptRequest , here you can catch loading of embedded objects (images, etc) and replace it with your own image. For example:

WebResourceResponse wr = new WebResourceResponse("", "", new FileInputStream("/sdcard/aaa.jpg"));
return wr;

You must detect yourself what you want replace by what.

On API<11 it may be more complicated to achieve this (I don't know yet how).

You can remove any Element from the page by injecting JavaScript into a WebView. Below is an example of how to inject JavaScrpt into a WebView to remove an element having its id:

public void onLoadResource(WebView view, String url) {
        super.onLoadResource(view, url);

         // Removes element which id = 'mastHead'
         view.loadUrl("javascript:(function() { " +  
                    "(elem = document.getElementById('mastHead')).parentNode.removeChild(elem); " +  
                    "})()");         
}

You can use the below code to check whether to load it on not. Where webview is the object for WebView.

webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                // TODO Auto-generated method stub
                super.onPageStarted(view, url, favicon);
                Toast.makeText(activity,"onPageStarted url :"+url, Toast.LENGTH_LONG).show();
            }
            @Override
                public void onLoadResource(WebView view, String url) {
                    // TODO Auto-generated method stub
                    super.onLoadResource(view, url);
                    Toast.makeText(activity,"Connecting url :"+url, Toast.LENGTH_LONG).show();
                }
          public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
          }
        });

I think this will help you.

该方法有2个参数,请在您的Web视图中将其覆盖,并舍弃以您要避免的域开头的网址。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM