我通常使用shouldOverrideUrlLoading
来拦截webview中的广告,但这次,新网站中的广告链接不会被捕获
public boolean shouldOverrideUrlLoading(WebView view, String url)
和
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
但它是在
public WebResourceResponse shouldInterceptRequest(final WebView view, String url)
因此,我使用了这个方法
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
Log.d("soidfzs", url);
WebResourceResponse webResourceResponse = null;
if (url.contains("https://googleads") || url.contains("doubleclick") || url.contains("google-analytics.com") || url.contains("adservice") || url.contains("securepubads")) {
Log.d("soidfzs", "here");
return webResourceResponse;
} else {
return super.shouldInterceptRequest(view, url);
}
}
但是,链接仍在加载并显示广告
那么,我应该返回什么呢?
发布于 2020-09-16 22:17:37
您将返回在if语句之前设置为null
的webResourceResponse
,您可以在该语句中检查请求是否可能是广告请求。
然而,shouldInterceptRequest
的documentation声明:
* @return A {@link android.webkit.WebResourceResponse} containing the
* response information or {@code null} if the WebView should load the
* resource itself.
因此,在返回null
时,您是在告诉WebViewClient加载资源本身,即满足广告请求并加载广告。
为了让请求滑动并返回您自己的值,您必须返回您自己的WebResourceResponse
实例,它不能为空才能正常工作。
return new WebResourceResponse(
"text/html",
"UTF-8",
null
);
在这里,我将mimeType
(第一个参数)设置为"text/html"
,尽管它也可能是其他值,比如"text/plain"
。
我设置了第二个参数-encoding
-to"UTF-8"
(和前面一样:可能是其他参数)。
现在到了最重要的部分:我将第三个参数data
设置为null
。
这会导致WebView获得一个有效的WebResourceResponse
实例,该实例不是null
,但没有数据,这反过来又不会导致任何加载。
请注意,这将触发WebViewClient#onReceivedError
,因为WebView客户端实际上无法加载任何内容。这本身不是一个问题,但如果您覆盖了onReceivedError
,就需要当心了。
https://stackoverflow.com/questions/61528252
复制相似问题