Using JavaScript / jQuery to detect if someone is using AdBlock

Standard

Let’s face it: ads are not cool. I know, but sometimes you have no other choice than to use them to pay your server / your coffee / whatever. And if you are using ads, you know that some people will not see your ads because they are using a plugin that blocks ads on your website. You want to reach these visitors and just say

“Hey, we know ads are not cool, but please make an exception for us or give us a small amount of money, just to support our work”

On Teen Quotes I am showing a friendly message in place of the only ad to say what I have to say. Here is what people with an ad blocker are seeing:
adblock

But let’s get back to the point: detect visitors that are using an ad blocker with JavaScript.

Some code

Let’s write some code. You’re going to write the most simple JS file you have ever written. Ready? Here it is:

var isNaughtyVisitor = false;

BOOM! That was fast, isn’t it? In fact, we don’t care about the variable name or its value, we just want to define a new variable. But this variable needs to be defined in a file called ads.js that you will include in your HTML. Why so? This is were it gets funny. Ad blockers are a little dumb, so when they see a file named something like ad.js or ads.js, they will block the request. And if the request was blocked… your variable will not be defined!

The second step is just to test in your regular JS file of your application if the variable was defined. This file needs to be include after the previous file, ads.js. You can add something like this:

$(document).ready(function() {
    // The div that will add to the DOM if the visitor is 
    // using an ad blocker
    var div = 'Your amazing HTML block here';
    
    // The script was never called, probably using an ad blocker
    if (typeof(isNaughtyVisitor) == "undefined") {
        // Insert the div wherever you want
        $("#footer").before(div);
        // Send the event to Google Analytics if you want to track
        ga('send', 'event', 'ads', 'hidden');
    // A friendly user!
    } else {
        // Send the event to Google Analytics if you want to track
        ga('send', 'event', 'ads', 'displayed');
    }
});

Pretty darn simple, and really effective. The downside is that friendly users will have to make an extra HTTP request. Yep, I know, it’s not fair for them.

Sounds great? Give me a follow on Twitter or learn more about me.