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.
4 Answers
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).
Comments
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); " + "})()"); } Comments
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.
4 Comments
The method has 2 params, override it in your webview and discard urls starting with the domain you want to avoid.