Android block ads in webview

adblock plus android github
ad blocker android + github
how to block ad servers
libadblockplus
ad server block list
ad blocking hosts file

I want to implement a mechanism in a custom webview client (without JavaScript injection) that can block ads. Is a way I can catch ads and replace them with other ads from a trusted source? Thanks

In your custom WebViewClient, you can override the function shouldInterceptRequest(WebView, WebResourceRequest).

From Android docs:

Notify the host application of a resource request and allow the application to return the data.

So the general idea is to check if the request is coming from an ad URL (plenty of black list filters out there), then return a "fake" resource that isn't the ad.

For a more in depth explanation plus an example, I recommend checking out this blog post.

How to block Ads on Android Webview - Adam Fils, Ads are annoying, i just had to say it. Today i will be showing you how to block Ads in Android Webview in 4 Steps. First, Let's create a function  I am about to roll out WebView AdBlocking in my android app. I want to know if this will effectively block ads or if there is more to be done say within the Webview itself which I have not modified. Basically I have a host file of stored in Android assets which lists hundred of ad server sites.

To implement this, you have two options:

  1. Use Javascript injected code to do this (which you explicitely said, don't want)
  2. In WebView, instead of "http://example.com" load "http://myproxy.com?t=http://example.com" (properly escaped, of course) and setup "myproxy.com" to be a proxy which will fetch the upstream page (given in "t" query parameter, or in any other way) and replace ads with the trusted ones before sending response to the client. This will be pretty complex, though, because ads can be in many forms, they're usually Javascript injected themselves and you'd probably need to rewrite a lot of URL's in the fetched HTML, CSS and JS files etc.

Hacking up an ad blocker for Android, Use WebViewClient.shouldInterceptRequest(WebView, String) to intercept requests; Check if the request URL belongs to one of the hostnames  In your custom WebViewClient, you can override the function shouldInterceptRequest(WebView, WebResourceRequest). From Android docs: Notify the host application of a resource request and allow the application to return the data. So the general idea is to check if the request is coming from an ad URL

I made a custom WebViewClient like:

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);
    }
}

And created an AdBlocker class like:

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();
}

}

And use this WebViewClient in your oncreate like:

 webview.setWebViewClient(new MyWebViewClient());

Anyone know how to do ad blocking on a webview in my app?, r/androiddev: News for Android developers with the who, what, where when and how of the Android community. Probably mostly the how. Here, you'll … How do I display mobile ads using Android WebView? To display ads in native Android applications, you can use WebView (see also WebView API). Below is an example: Add WebView in the layout Here is an example WebView element in the activity layout: Require Internet permission in the manifest Setup WebView

AdBlockedWebView-Android, AdBlockedWebView-Android. An Implementation of WebView with Ad-blocked Interface. Blocks Banner And Video Apps From Web Page. N|Solid. Basic useful​  I am trying to block ads in an android webview. The think that , i dont only show one website, so i am not able to block ads from a JavaScript injection. Adblock is so useful , and I believe there should be a adblock library which will block ads in a webview.

block ads in a webview, I am trying to block ads in an android webview. The think that , i dont only show one website, so i am not able to block ads from a JavaScript  xda-developers Android Development and Hacking Android Software and Hacking General [Developers Only] Webview with ad blocking by Stasheck XDA Developers was founded by developers, for developers. It is now a valuable resource for people who want to make the most of their mobile devices, from customizing the look and feel to adding new functionality.

Blocks web trackers/ads in webview (#194) · Issues · Space Cowboy , Blocks web trackers/ads in webview. This app is great but lacks https://www.​hidroh.com/2016/05/19/hacking-up-ad-blocker-android/. This app is great but  I have a question regards ads related to webview. I have an application and i placed admob banner at the bottom of the app now above the bottom fragment there is webview and other fragments in the app so does it violates the admob as banner keep showing in the app while other website open in webview?

Comments
  • This is the correct answer. The linked blog post contains a detailed explanation with example code.
  • In case of Javascript injection can you provide me an example or if you have a link that will help me it would be great.
  • Doing it JS way won't be easy neither, I'm afraid. You can get AdBlock source code here: adblockplus.org/en/source, and you'd need to modify it a bit. I'm not aware of any other good open source projects of this kind.
  • can you help me with more details about your second answer..some code steps maybe..from the last time I've struggled with all sorts of hints but nothing worked (or it's working only on some api versions)
  • @kamituel...i've found this how to configure a local proxy stackoverflow.com/questions/4488338/webview-android-proxy but I don't understand how to load a url from that local proxy