Detect an ad blocker with pure JavaScript

OpenJavaScript 1
Reading Time: 4 minutes 🕑

Last updated: September 27, 2022.

From the user perspective, ad blockers have become increasingly popular as a means to prevent annoying ads from negatively impacting user experience.

On the other hand, publishers sometimes need to generate revenue to keep services free-to-use.

So there can be a clash of interests between users and publishers.

In this tutorial, we show you how to detect whether a user is using an ad blocker using pure JavaScript.

We also suggest some solutions for handling the result. We suggest two good strategies:

We absolutely do not advocate blocking user’s access to content!

This is likely to negatively impact your website or page’s SEO rankings by increasing the bounce rate. And, if poorly implemented, blocking content in this way can prevent some users accessing your site at all, even if their ad blocking software is deactivated!

How ad blocking software works

In case you are not already familiar with it, most ad blocking browser extensions are relatively simple in their procedure.

The software waits for the elements of a page to load and then changes the CSS of elements it detects to be advertisements.

Usually, this is done by detecting keywords in an elements class list such as ‘adsbygoogle’, or something similar.

Once the ad blocking software has detected an element it has reason to believe is an ad, it changes the CSS styling of that element to a height or width of 0px or to a display value of none.

What you need to do to detect ad blocking software is therefore test to for a change in the CSS of a probable ad element after its CSS properties have been changed.

If a change is detected, a user is likely running ad blocking software.

Use JavaScript to set up ‘ad bait’

Because of the way ad blocking software works, it is possible to create an ‘ad bait’ element by adding ad-related keyword into an element’s class list. The element’s CSS properties can then be checked to determine whether they have been altered by an ad blocker upon being inserted onto the page.

Below is a simple but functional ad blocker code. It inserts an element to the page with the class adsbygoogle. It then selects the element, gets its CSS properties using getComputedStyle and checks to see if these have been modified. If so, an adblocker is being used.

Note that the code inside the function executes with a 1000 millisecond time delay, which is usually long enough for the ad blocker to kick in:

/*** Ad blocker detection utility function ***/

// 1) Ad block detection function:
function adBlockCheck() {
    setTimeout(function() {
        document.body.innerHTML += `<div class="adsbygoogle" id="test-ad"></div>`;
        const testAd = document.getElementById('test-ad');
        const testAdStyle = getComputedStyle(testAd);

        if (testAdStyle.display === 'none') {	
            // Adblock enabled: do something
        } else {	
            // Adblock disabled: do something
        }
    },1000)
}

// 2) Call the function:
adBlockCheck()
    

Handling the result

You may be tempted to block the user’s access to the page if an ad blocker is detected. But this is generally a bad strategy.

First, it is almost certainly going to increase the page bounce rate, and have a negative knock-on effect for SEO rankings.

And, second, if for some reason the ad block detection falsely detects the existence of an ad blocker, the user is effectively blocked from a page entirely. This is unlikely but a very bad outcome, even if only in limited cases.

A better way is to alternate content.

Strategy #1: Alternate content

If a user is employing an ad blocker, third-party ads will not be rendered to the page.

But you can still render your own content in their place!

For example, do you have a service (e.g. a course) you would like to promote? You can use this opportunity to do so!

Using this solution, the user either sees an ad or some promotional content, which is in both cases good from a publisher’s perspective.

You can achieve this outcome by modifying the boilerplate ad detection code above to add content if an ad blocker is detected.

/*** Implementing alternative content ***/

function adBlockCheck() {
    setTimeout(function() {
        document.body.innerHTML += `<div class="adsbygoogle" id="test-ad"></div>`;
        const testAd = document.getElementById('test-ad');
        const testAdStyle = getComputedStyle(testAd);

        if (testAdStyle.display === 'none') {	
            const adContainer = document.getElementById('ad-container');
            
            const myImg = document.createElement('img');
            myImg.src = 'https://your-imgage-url.com/image.png';
            adContainer.append(myImg);
        } 
    },1000)
}

Strategy #2: Use a persuasion banner

Don’t have a service you would like to promote in place of your ads?

Then an alternative strategy is to create a persuasion banner. This is a simple banner that can appear somewhere on the page that can be used to try and appeal to the user’s sense of fairness to deactivate their ad blocker.

After all, if you are offering a free service, your most loyal user’s will probably want to support you!

You can use this technique by modifying the code to something like this:

/*** Implementing a persuasion banner ***/

function adBlockCheck() {
    setTimeout(function() {
        document.body.innerHTML += `<div class="adsbygoogle" id="test-ad"></div>`;
        const testAd = document.getElementById('test-ad');
        const testAdStyle = getComputedStyle(testAd);

        if (testAdStyle.display === 'none') {	
            const banner = document.createElement('div');
            banner.innerHTML = `
            <h3>Ad blocker detected</h3>
            <p>To keep our services free, we use advertising on this site. Please consider supporting us by disabling your ad blocker.</p>
            `
            banner.setAttribute('class', 'alert');
            banner.style = "background: red; color: whitesmoke; width: 100%; padding: 0.8rem; font-size: 1.2rem";
            document.body.prepend(banner);
        } 
    },1000)
}

The output will look something like this if a user is using an ad blocker:

Ad blocker detection banner

If the user is not using an ad blocker, the banner will not appear.

Summary

Implementing ad block detection is JavaScript is relatively straightforward.

How to handle the result is not so simple. Be careful not negatively impact the functionality of your site.

If you really want a user to see ads, try appealing to their better nature with a persuasion banner. After all, if you are delivering great content, it is likely that your users will want to support you.

Related links