How to Detect an Ad Blocker

By  on  

One of the unspoken rules of the internet is that most content is "free"... at the cost of webpage being littered with advertisements and trackers. This was't a big problem in the early internet days but trackers and advertisements have become so intrusive and unapologetically aggressive that you almost need to use an ad blocker browser extension.

Ad Blocker Plus is hugely popular and a browser like Brave boasts about being centered around ad blocking. Oftentimes I'll go to a site and see a modal as me to disable my ad blocker, which got me to thinking about the best way to detect an ad blocker. After a variety of tests and experimentation, I found a really simple way to detect an ad blocker!

Essentially my method attempts to load Google's ad service JavaScript file, and if the request fails, it's likely due to the user having an ad blocker:

// Determines if the user is likely using an ad block extension
async function checkAdBlocker() {
  // Used to cache the result
  let isBlocked;

  async function tryRequest() {
    try {
      return fetch(
        new Request("https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js", {
          method: 'HEAD',
          mode: 'no-cors'
        }))
        .then(function(response) {
          // Google Ads request succeeded, so likely no ad blocker
          isBlocked = false;
          return isBlocked;
        }).catch(function(e) {
          // Request failed, likely due to ad blocker
          isBlocked = true;
          return isBlocked;
        });
    } catch (error) {
      // fetch API error; possible fetch not supported (old browser)
      // Marking as a blocker since there was an error and so
      // we can prevent continued requests when this function is run
      console.log(error);
      isBlocked = true;
      return isBlocked;
    }
  }

  return isBlocked !== undefined ? isBlocked : await tryRequest();
}

// Using the ad block checker
const usingBlocker = await checkAdBlocker();

The logic behind this is as follows:

  • Google's ad file, adsbygoogle.js, is the perfect sample file, because it is considered enemy number 1 -- the first file an ad blocker would want to block due to Google's ad service popularity
  • The file is also paramount to Google's business so 99.999999999% uptime is practically guarateed
  • There's little chance a network issue would come into play; false positives may come from network connectivity issues or a bad service worker
  • If you don't consider adsbygoogle.js your best sample file, you can easily switching it out for any other URL

From a content creator perspective, a navigator property that would let you know if an ad blocker was employed would be ideal...but that isn't happening anytime soon (...never, really). Using simple snippets like this, however, provide a reasonable hint toward the user enabling an ad blocker!

Recent Features

  • By
    Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

  • By
    9 Mind-Blowing Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

Incredible Demos

  • By
    Scroll IFRAMEs on iOS

    For the longest time, developers were frustrated by elements with overflow not being scrollable within the page of iOS Safari.  For my blog it was particularly frustrating because I display my demos in sandboxed IFRAMEs on top of the article itself, so as to not affect my site's...

  • By
    MooTools Zebra Tables Plugin

    Tabular data can oftentimes be boring, but it doesn't need to look that way! With a small MooTools class, I can make tabular data extremely easy to read by implementing "zebra" tables -- tables with alternating row background colors. The CSS The above CSS is extremely basic.

Discussion

  1. Using this code to “know” if your end user has an ad blocker installed is handy information… however what are you going to do with that information?

    If your intent is to alienate your audience by holding your content hostage until they whitelist your site… you will find that you will quickly lose that audience. If you want to place subtle hints, go for it, but putting up physical blockers causes tension, frustration and anger (and won’t get any adblock users to whitelist you).

    • @Stephen, It is not necessary to ask users to whitelist you (although this is not bad, in my opinion), and even more so to demand something and block content. You can, in case of detection of Ad Blocker, insert alternative advertising (a referral link to some service that you use or something similar).

      Indeed, in fact, the majority of users of ad blockers are not against advertising in general, but against intrusive, excessive, and inappropriate advertising.

      But it so happened that after installing the blocker, you don’t need to blacklist each site you visit – they are all already in it. Both that have more advertising than useful content, and those that do everything to not inconvenience their visitors.

  2. content editor

    Stephen, why should we share our content with you if you’re not willing to pay neither accept ads ? Just please give me one single reason.
    Philanthropy ?

  3. How more accurate is this method compared to simple analysis of HTML elements? Making an extra request is not good, I think.
    I use a very simple thing in my projects:

    window.onload = function() {
    	setTimeout(function() {
    		var ad = document.querySelector("ins.adsbygoogle");
    		if (ad && ad.innerHTML.replace(/\s/g, "").length === 0) {
    			//blocked
    		} else {
    			// not blocked
    		}
    	}, 2000); // here is 1 or 2 secs delay
    };
    

    I really did not test it thoroughly, but it seems to work fine.

  4. Mickey Aharony

    I have two ad blockers running. I find sites detect ad blocker (plus) but the second one I use goes undetected. Or vice versa.

  5. Captain

    Whichever method is used, it’s easy enough to just disable javascript for the page and enjoy the ‘unscripted’ page. Re-enable when you leave and annoying “Do this or else…” messages are gone.
    All these methods for detecting ad-blockers have an Achilles Heel by relying on javascript loading to detect if javascript is loading or not. Javascript is thankfully 100% unnecessary for most sites that try to block you before you can read the page.

  6. Too bad your sample code only works with ECMA Script 2016-enabled browsers. This won’t work in any browser before 2016.

  7. Somedude

    I’ve got nothing against most advertisements, or sites that display them. But the few advertisements that make the screen flash, have extensive distracting animations, insert themselves at annoying times, pretend to be download buttons for content, result from unnecessary tracking or ignore opt-out requests for tracking, and more ruin it for the rest. I don’t run an ad blocker to block ads. I run an ad blocker to block horrible ads.

  8. Bruno

    Hey Brother, why did you use the “await” directive there

    // Using the ad block checker
    const usingBlocker = await checkAdBlocker(); 

    Every JavaScript linter is throwing me a notice that reads:
    The ‘await’ operator can only be used in an ‘async’ function

    Having said that! Thank you for the code. Really useful!

  9. Paulo

    This isn’t working, or I’m wrong?

  10. Jardiel Valadão

    Guys change this:

    const usingBlocker = await checkAdBlocker();
    

    for this

    const usingBlocker = async function () {
         return await checkAdBlocker();
    }
    // Using the ad block checker
    usingBlocker().then((res) => { 
         if(res) {
    	console.log('AdBlock is enabled');
         } else {
    	console.log('AdBlock is NOT enabled');
         }
    });
    

    WORKING FINE!

  11. John

    Very interesting approach based on connection to google. I have found how to get it working when we are not using google (different url, don’t know which to use then) https://dev-bay.com/javascript-detect-adblock-and-display-your-content/ but it sound for me strange to check if adblocks works or not just by checking the height of ad container, what do you think about it?

  12. Chris Zuber

    There’s valid use of this sort of technique outside of ads and tracking, though the specific script would likely yield false positives. Privacy Badger, for example, blocks third-party resources that it encounters on multiple sites and suspects of being a tracker – this can cause CDN resources and such to fail to load. I’ve had it block my CDN entirely, which is hugely problematic!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!