H3XED

How To Detect AdBlock Using JavaScript

Nov 13, 2014   Web Development   Nick Vogt   Comments
Please note that this post is over a year old and may contain outdated information.
There are a number of different ways to detect if the user has an ad blocker. It can be useful information if you want to hide stray elements when ads are blocked, such as ad containers, or display a message to your users.


Method 1: Missing Variable


If you have control over the external script that you're including, or can be assured the script will contain a variable or object that you can normally access, you can check for the existence of it after the script has loaded.

<script src="https://www.the-ad-server.com/ad-script.js"></script>
<script>
// If we know the script contains "testVar", check if it exists:
if (typeof testVar === 'undefined') {
    // Ad script was blocked!
}
</script>


Method 2: Element Height


You can test the height of your ad element after the script loads to see if the ad is successfully injected.

<script>
var ad = document.getelementById('ad');
var startHeight = ad.clientHeight;
</script>
<script src="https://www.the-ad-server.com/ad-script.js"></script>
<script>
// Wait 0.5 seconds to give the ad time to load
setTimeout(checkHeight, 500);
function checkHeight() {
    if (ad.clientHeight <= startHeight) {
        // Ad script was blocked!
    }
}
</script>


Method 3: script.onerror


You can use the onerror event to determine if your external script include failed.

<script>
var js = document.createElement('script');
js.onerror = function() {
    // Script failed (probably due to an ad blocker)
};
js.src = 'https://www.the-ad-server.com/ad-script.js';
document.head.appendChild(js);
</script>

This only works on newer browsers. I tested it on the latest versions of Chrome and Firefox, and according to this source it works back to IE9.


Method 4: Dummy Ad


Similar to method 1, but in the event that you don't have control over the ad script. You can create a dummy script include that looks just like an ad script, to see if your test variable exists. Keep in mind that this will incur an additional http request, so it's not the most ideal solution.

<script src="/banner/ad-server.js"></script>
<script>
if (typeof testVar === 'undefined') {
    // Ad script was blocked!
}
</script>

In this example, we use the location /banner/ad-server.js because you can be nearly certain any ad blocker will block that URL. And inside ad-server.js you just have something like:

var testVar = 'test';
It's possible your dummy ad script will be blocked while another ad script won't be, so again this solution is not the most ideal.
Share This Post
Twitter

Comments (0)

Share This Post
Twitter
H3XED © Nick Vogt   RSS   Policies   Twitter