Is there a way to block ads in an Android WebView? I am building app that lets users browse web pages, but need to block ads. Its basically a custom browser, but I need to get rid of ads.
What is my best option?
Based on: https://github.com/adblockplus/adblockplusandroid
saw this: https://gist.github.com/rjeschke/eb1bb76128c5e9a9e7bc
import java.io.File;
import java.util.regex.Pattern;
import org.adblockplus.android.ABPEngine;
import org.adblockplus.libadblockplus.FilterEngine.ContentType;
import android.content.Context;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class BlockingWebViewClient extends WebViewClient
{
private ABPEngine engine;
private static final Pattern RE_JS = Pattern.compile("\\.js$", Pattern.CASE_INSENSITIVE);
private static final Pattern RE_CSS = Pattern.compile("\\.css$", Pattern.CASE_INSENSITIVE);
private static final Pattern RE_IMAGE = Pattern.compile("\\.(?:gif|png|jpe?g|bmp|ico)$", Pattern.CASE_INSENSITIVE);
private static final Pattern RE_FONT = Pattern.compile("\\.(?:ttf|woff)$", Pattern.CASE_INSENSITIVE);
private static final Pattern RE_HTML = Pattern.compile("\\.html?$", Pattern.CASE_INSENSITIVE);
public void start(Context context)
{
final File basePath = context.getFilesDir();
this.engine = ABPEngine.create(context, ABPEngine.generateAppInfo(context),
basePath.getAbsolutePath());
// Additional steps may be required here, i.e. :
// - subscription selection or updating
// - maybe also setting other options (like AcceptableAds)
// It might also be a good idea to delay the first calls until
// everything is loaded, have a look at AndroidFilterChangeCallback
// and ABPEngine.create()
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url)
{
// Determine the content
ContentType contentType = null;
if (RE_JS.matcher(url).find())
{
contentType = ContentType.SCRIPT;
}
else if (RE_CSS.matcher(url).find())
{
contentType = ContentType.STYLESHEET;
}
else if (RE_IMAGE.matcher(url).find())
{
contentType = ContentType.IMAGE;
}
else if (RE_FONT.matcher(url).find())
{
contentType = ContentType.FONT;
}
else if (RE_HTML.matcher(url).find())
{
contentType = ContentType.SUBDOCUMENT;
}
else
{
contentType = ContentType.OTHER;
}
// Check if we should block ... we sadly do not have the referrer chain here,
// might also be hard to get as we do not have HTTP headers here
if (engine.matches(url, contentType, new String[0]))
{
// If we should block, return empty response which results in a 404
return new WebResourceResponse("text/plain", "UTF-8", null);
}
// Otherwise, continue by returning null
return null;
}
}
It is done already: https://github.com/adblockplus/libadblockplus-android
You can put it at xml:
<org.adblockplus.libadblockplus.android.webview.AdblockWebView
android:id="@+id/main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>