浏览器Android阻止webview中的广告 1 周,3 日 Questions & Answers 13406 我想在一个定制的webview客户端(没有JavaScript注入)中实现一种机制来阻止广告。这是一种捕获广告并用来自可信来源的其他广告替换它们的方法吗? 谢谢
# 1 楼答案 我做了一个定制的WebViewClient比如: public class MyWebViewClient extends WebViewClient { @Override public void onPageFinished(WebView view, String url) { } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.endsWith(".mp4")) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse(url), "video/*"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); view.getContext().startActivity(intent); return true; } else if (url.startsWith("tel:") || url.startsWith("sms:") || url.startsWith("smsto:") || url.startsWith("mms:") || url.startsWith("mmsto:")) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); view.getContext().startActivity(intent); return true; } else { return super.shouldOverrideUrlLoading(view, url); } } private Map<String, Boolean> loadedUrls = new HashMap<>(); @SuppressWarnings("deprecation") @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { boolean ad; if (!loadedUrls.containsKey(url)) { ad = AdBlocker.isAd(url); loadedUrls.put(url, ad); } else { ad = loadedUrls.get(url); } return ad ? AdBlocker.createEmptyResource() : super.shouldInterceptRequest(view, url); } } 创建了一个AdBlocker类,比如: public class AdBlocker { private static final Set<String> AD_HOSTS = new HashSet<>(); public static boolean isAd(String url) { try { return isAdHost(getHost(url)); } catch (MalformedURLException e) { Log.e("Devangi..", e.toString()); return false; } } private static boolean isAdHost(String host) { if (TextUtils.isEmpty(host)) { return false; } int index = host.indexOf("."); return index >= 0 && (AD_HOSTS.contains(host) || index + 1 < host.length() && isAdHost(host.substring(index + 1))); } public static WebResourceResponse createEmptyResource() { return new WebResourceResponse("text/plain", "utf-8", new ByteArrayInputStream("".getBytes())); } public static String getHost(String url) throws MalformedURLException { return new URL(url).getHost(); } } 在你的oncreate中使用这个WebViewClient,比如: webview.setWebViewClient(new MyWebViewClient());
# 1 楼答案
我做了一个定制的
WebViewClient
比如:创建了一个AdBlocker类,比如:
在你的
oncreate
中使用这个WebViewClient
,比如: