[英]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. 我正在开发一个android应用程序,其中有时会显示一个webview,其中显示了一个网页。 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? 每个资源都通过onLoadingRecource()
方法...这是我可以找到解决方案的地方吗? 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. 从API 11开始,提供了WebViewClient.shouldInterceptRequest ,您可以在这里捕获嵌入式对象(图像等)的加载并将其替换为您自己的图像。 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). 在API <11上,实现此目标可能会更复杂(我尚不知道如何实现)。
You can remove any Element from the page by injecting JavaScript into a WebView. 您可以通过将JavaScript注入WebView来从页面中删除任何Element。 Below is an example of how to inject JavaScrpt into a WebView to remove an element having its id: 以下是如何将JavaScrpt注入WebView中以删除具有其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是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视图中将其覆盖,并舍弃以您要避免的域开头的网址。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.