🌓

Detect and Block Adblock in one simple line of code Detect when a user has got an Adblock plugin enabled in just one line of code and show them a friendly message, another ad, block access or else

by
on December 14, 2015
(5 minute read)

I want to show you how to detect when a user to your site has got an ad blocker extension (AdBlock, Adblock Plus, uBlock Origin and many others) enabled, and do so in just one line of JavaScript/jQuery code without the need of plugins or libraries.

You will also get examples of the HTML and CSS code you need to use, instructions on how to track Adblock users through Google Analytics Events and also a configuration link to a Google Analytics Segment ready to use in your own sites so you can measure how many Adblock users visit your site as well as key data to analyze further revenue strategies for your blog or website.

Most of blogs out there use some kind of revenue scheme to pay for server expenses and compensate on the hard work put on them. Same goes for my own personal blog you are reading right now. In this blog, I talk a lot about technology and advanced programming so the main audience is tech savvy, which increases the chance they’ve got some kind of Adblocker extension installed. Comparing stats to other blogs I know, this one earns about 20% of what the others are generating regarding number of visitors, countries and other factors… After tracking info through the Google Analytics Segment I saw that 29% of my readers use Adblock software, that’s one of every three visitors.

Thing is, I understand why a lot of people use online advertisement blocking software, I myself I’m one of those. As an online and software professional, one of my main objectives is to make websites and interfaces as usable as possible so I make sure not to insert annoying ads. Although a lot of of websites out there don’t follow the same principle. So the best way to go is to block them altogether and not to see any ads, you have the right to do so. And because we are in a free world I also think website owners are in the right to detect and/or block these ad blockers too.

Detecting and Blocking AdBlockers

Let’s make one thing clear, you cannot disable someone’s AdBlock plugin, that would be a huge security risk from the browser’s perspective. But you can detect it and then act upon it. There’s a lot of different actions to take once you’ve detected someone using an Adblocker, here’s some ideas:

  • Show them a friendly message that your blog is sustained by advertisement and hope they whitelist you;
  • Show them a replacement advertisement; or
  • Block access to the website until they disable it. This last one is quite harsh and you will lose many visitors (not recommended).

In order to remedy this in a nice way without disturbing readers (they installed an Adblock plugin for a reason) I choose the second option and place a custom-made good-looking non-intrusive banner, designed by myself, so none of the ad blocking lists have caught on it yet, the design of it is really clean, minimal and seamless, so that it doesn’t bother anyone. Here’s the difference:

Without Adblock the visitor sees a Google Adsense advertisement:

With Adblock enabled the advertisement is removed:

With Adblock detector, the Google Adsense is hidden and my custom-made ad is shown:

Awesome! Isn’t it? Fact is, it’s really simple to get it done and you just need one line of jQuery code (for JavaScript read further). Whatever you do, please be nice enough so your users don’t get upset. If this solution becomes mainstream and people start to abuse it, Ad Blockers will develop some new way to block ad block blockers, boom.

Code to detect Adblock

jQuery

Paste this code inside $(document).ready()

$.ajax('showads.js').fail(function(d){if(d.status===0 || d.statusText == 'error'){$('html').addClass('ab');}});

If an Adblock is detected, it will add an ab CSS class to the html tag. You can now do something like this:

CSS

Have a hidden element and only show it when an Adblock is detected (i.e. a replacement banner or message to the visitor):

/* Anti Adblock */
.post .ab {
 display: none;
}
html.ab .post .ab {
 display: inline-block;
}

HTML

In my case, it’s an image with a link:

<a href="https://trendliker.com/user/xavi" class="ab"><img src="//xaviesteve.com/8hd23fh5.png"></a>

Remember to use random numbers or letters as the image name so there’s no recognizable pattern to block through Adblock filters. The sorter the better.

How it works and the JavaScript code

The code above uses jQuery, the way it works is that it does an asynchronous AJAX call to a file that has a suspicious-looking name to any Ad Blocker, in this case: showads.js. So the process in vanilla JavaScript is pretty simple, you just need to run an AJAX call (using the JS framework of your choice or a micro-library such as Qwest) and call showads.js (the file shouldn’t exist in your server and normally return a 404 error). If the response is a 404 Not Found then you know that the user is not using any ad blocker, if there’s some kind of network or connectivity error detected (an adblocker has blocked it) then the user is using an adblocker.

Friendly messages

Here’s a few examples of friendly messages you can show your user in case you want to opt for the “friendly message” way:

  • I see you are using an AdBlocker, it’s totally OK. Would you mind whitelisting this site? We don’t show annoying ads.
  • Please disable your Adblocker to help keep this site running.
  • So normally there would be an ad in this spot. But you’re using an Ad-Blocker like a boss; Like a boss who hates ads. & that’s cool, except that OkCupid is Ad-Supported & we need money to run this beast. (via OkCupid)

Tracking AdBlockers in Google Analytics

You can track users using AdBlock through Google Analytics events:

$.ajax('showads.js')
 .fail(function(d){
  if ( d.status===0 || d.statusText == 'error' ){
   $('html').addClass('ab');
   try{
    ga('send', {
     hitType: 'event',
     eventCategory: 'User',
     eventAction: 'Adblock',
     eventLabel: 'on'
    });
   }catch(e){}
    }else{
     try{
      ga('send', {
       hitType: 'event',
       eventCategory: 'User',
       eventAction: 'Adblock',
       eventLabel: 'off'
      });
     }catch(e){}
    }
});

From here you can easily create a Google Analytics Segment to analyze your users behavior and be able to compare both adblock users and non-adblock users. I have create segment for you and you can included in your Google Analytics by following this link:

Google Analytics Segment – Users with Adblock enabled

Bonus: Dealing with NoScript and JavaScript-disabled users

Now that we know how to detect AdBlock, you can also detect NoScript users. The idea is the same as the above, but the other way around. You just need a few modifications:

  1. Hard-code the .ab class in the html tag
  2. Modify the JavaScript code so it removes html.ab class when a 404 error is detected

Things I’m buying on Amazon this week

This is an extreme measure, while there are a lot of users that use AdBlocking plugins, not too many people have JavaScript disabled nowadays.

What are your thoughts on this? Do you think it is right for us bloggers to do so? Let me know in the comments!

Free 100% online banking account

💳 Get your free debit Mastercard

One comment

  • Some Mike says:

    Thank you Xavi, this is great.

    I am with you on this, everyone is free to block ads, and as content creators we are free to block them. Period. I spend a lot of hours working on my blog with thousands of people every day benefiting from it and it is a shame I can’t even pay for the server expenses

Treasure Chest

Get notified of new projects I make
Usually one email every 3 months

Follow me for cool new products and interesting findings on graphic design, web development, marketing, startups, life and humor.


/*Twitter*/ !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); /*Facebook (function(d, s, id) {var js, fjs = d.getElementsByTagName(s)[0];if (d.getElementById(id)) {return;}js = d.createElement(s); js.id = id;js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=28624667607";fjs.parentNode.insertBefore(js, fjs);}(document, 'script', 'facebook-jssdk'));*/ /*Google+*/ window.___gcfg = {lang: 'en-GB'};(function() {var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;po.src = 'https://apis.google.com/js/plusone.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);})();