Detect Adblockers

— 5 minute read

permalink

Today I needed a way to detect an adblocker. You might think why? In this case, I wanted to verify some user data with an external system, but adblockers will block this call (mainly ghostery).

So I tried and research ways to detect adblockers!

When doing my research, I came across several ways of which some in theory work, but not for all browsers/adblockers. Let me walk you through the options we have.

JavaScript onError callback permalink

This method, I only found late in the game and is the solution I went for. I like the simplicity, and it worked for by far the most combinations I tried!

So in the HTML we add the following:

<!-- Fake js script to inject, adblockers will block this script load -->
<script
async
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
onerror="adBlockFunction();"
>
</script>

The idea is this script will be blocked by adblockers and if it does it will run the adBlockFunction.

So the function:

var adblocker = document.getElementById('adblock-message');
adblocker.style.display = 'block';

Then we can have a simple adblocker div which is hidden by default.

<div id="adblock-message" class="hidden">Sorry, you have your adblocker on!</div>

As mentioned, this way works for most combination of browsers/adblockers.

Alternative JavaScript method permalink

Another way, you'll come across quite a lot if defining a JavaScript file like this:

<script src="/js/ads.js"></script>

inside:

var canRunAds = true;

And then have a JavaScript as such:

if (window.canRunAds === undefined) {
var adblocker = document.getElementById('adblock-message');
adblocker.style.display = 'block';
}

This is almost the same as solution one, but I found that it doesn't work with Adblock in the latest Chrome.

CSS Height permalink

Another way, is by using a fixed "ad" in your html:

<div
id="detect"
class="ads ad adsbox doubleclick ad-placement carbon-ads"
style
="background-color:red;height:300px;width:300px;position: absolute;left:0;top:0;"

>

&nbsp;
</div>

This should be blocked by adblockers so if we then go and check for the height, it shouldn't work:

var testAd = document.getElementById('detect');
window.setTimeout(function() {
if (testAd.offsetHeight === 0) {
var adblocker = document.getElementById('adblock-message');
adblocker.style.display = 'block';
}
testAd.remove();
}, 100);

As mentioned very cool solution, but not rock solid!

Try them all on Codepen.

See the Pen Detect Adblockers by Chris Bongers (@rebelchris) on CodePen.

Other ways? permalink

Let me know if you know of any other ways, without using any plugin!

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter