WebView 本身不具備廣告識別能力,最可行的方案是在載入階段攔截已知廣告域名/URL,阻止其請求發出。
webView.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (isAdUrl(url)) {
// 回傳空回應,阻止載入
return new WebResourceResponse("text/plain", "utf-8", new ByteArrayInputStream(new byte[0]));
}
return super.shouldInterceptRequest(view, request);
}
});
isAdUrl() 可維護一份廣告域名黑名單(如 doubleclick.net, googlesyndication.com 等),或整合開源規則(EasyList、EasyPrivacy)。
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (isAdUrl(url)) return true; // 攔截,不載入
return false;
}
注意:此方法僅能攔截主框架導航,無法攔截頁面內的圖片、Script、iframe 請求。
引入方式(以 AdBlockWebView 為例):
implementation 'com.github.adblockplus:adblockplus-android:2.0.0'
// 使用 AdBlockWebView 替換原生 WebView
即使請求被攔截,頁面可能仍保留空白廣告區塊。可在 onPageFinished 注入 CSS:
String css = "iframe[src*='ads'], .ad-banner, #google_ads_iframe { display: none !important; }";
webView.evaluateJavascript(
"var style = document.createElement('style'); style.innerHTML = `" + css + "`; document.head.appendChild(style);",
null);
Android WebView 去除廣告的核心是請求攔截 + 規則庫。推薦使用 shouldInterceptRequest 搭配開源規則(EasyList),並輔以 CSS/JS 隱藏殘留容器。若專案允許,直接整合成熟的 AdBlockWebView 可大幅降低開發成本。