首页 > 解决方案 > 如何使用 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);
                }

            }

但是,链接仍在加载和广告显示

那么,我应该返回什么?

标签: androidwebview

解决方案


您正在返回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#onReceivedErrorWebView 客户端基本上无法加载任何内容。这本身不是问题,但需要注意以防您覆盖onReceivedError.


推荐阅读