android - 如何使用 WebResourceResponse 拦截广告 shouldInterceptRequest
问题描述
我通常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);
}
}
但是,链接仍在加载和广告显示
那么,我应该返回什么?
解决方案
您正在返回webResourceResponse
您在 if 语句之前设置的内容,null
在该语句中您检查请求是否可能是针对广告的。
然而,文档指出shouldInterceptRequest
:
* @return A {@link android.webkit.WebResourceResponse} containing the
* response information or {@code null} if the WebView should load the
* resource itself.
因此,在返回null
时,您是在告诉 WebViewClient 加载资源本身,即完成广告请求并加载广告。
为了让请求滑动并返回您自己的值,您必须返回您自己的WebResourceResponse
实例,该实例不能为 null才能正常工作。
return new WebResourceResponse(
"text/html",
"UTF-8",
null
);
在这里,我将mimeType
(第一个参数)设置为"text/html"
,尽管它也可能是其他东西,比如"text/plain"
.
我将第二个参数——<code>encoding——设置为"UTF-8"
(和以前一样:可能是别的东西)。
现在是最重要的部分:我将data
第三个参数设置为null
。
这会导致 WebView 获得一个有效的WebResourceResponse
实例,该实例不是null
但没有数据,这反过来又不会导致任何加载。
请注意,这将触发WebViewClient#onReceivedError
WebView 客户端基本上无法加载任何内容。这本身不是问题,但需要注意以防您覆盖onReceivedError
.
推荐阅读
- protractor - 如何从量角器中的外部函数返回整数作为承诺?
- c# - 在 C# 中使用线程异步执行语句
- javascript - 那么为什么不能在非异步函数中使用 await 呢?
- java - 为 ListView 索引设置存储的背景颜色时出现问题
- c++ - 智能指针、this 和构造函数
- java - Apache Lucene QueryParser.parse 未在 FuzzyQuery 上使用分析器
- python - 检查 pandas 数据框中的一系列单元格是否为 NaN 比使用 for 循环、math.isnan() 和 df.iloc() 更快的方法?
- android - 阴影映射在 Android 上的 OpenGL ES 3.0 中不起作用
- java - 无法在之间传递数据
testng 套件中的标签 - php - PHP foreach 循环正在渲染一个额外的列表项