Languages
[Edit]
EN

JavaScript - how to detect if adblock is enabled?

6 points
Created by:
JustMike
3488

In this article, we're going to have a look at how to detect if ads are blocked in JavaScript. By default there is no any universal variable that indicates that, ads are blocked or not.

There are tricks how tomake adblock test:

  • check if ads scripts are loaded correctly (onload and¬†onerror events);
    example path:
    • https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js
  • check if ads elements are¬†mounted correctly in DOM,
  • try to load some fake js file that pretends¬†advertisements and check if is loaded or not - this approach is universal;
    example paths:
    • /js/ads.js,
    • /scripts/advertisement.js,
  • try to create some fake element that pretends¬†advertisements and check if is blocked - this approach is universal.

Check below example to see how it works:

1. Fake advertisiement script test example

If final status is equal to 0 it means, it means adblock is enabled.

Note: this approach is universal.

// ONLINE-RUNNER:browser;

function checkAdsBlocked(callback) {
  	var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState == XMLHttpRequest.DONE) {
          	callback(xhr.status == 0);
        }
    };

    xhr.open('GET', '/scripts/advertisement.js?' + Math.random(), true);
    xhr.send(null);
}

// Usage example:

checkAdsBlocked(function(adsBlocked) {
    console.log('adsBlocked: ' + adsBlocked);
});

2. Fake advertisements element test example

If height of created fake element will be 0 it means adblock is enabled.

Note: this approach is universal.

// ONLINE-RUNNER:browser;

function checkAdsBlocked(callback) {
    var test = function() {
        var hAds = document.createElement('div');

        // we dont want to see fake element on page
        hAds.style.position = 'absolute';
        hAds.style.left = '-100px';
        hAds.style.top = '-100px';

        // class="adsbox" causes blocking content
        hAds.className = 'adsbox';
        hAds.innerHTML = ' ';

        document.body.appendChild(hAds);

        setTimeout(function(){
            callback(hAds.offsetHeight == 0);

            document.body.removeChild(hAds);
        });
  	};

    if (document.body) {
      	test();
    } else {
      	window.addEventListener('onload', test);
    }
}

// Usage example:

checkAdsBlocked(function(adsBlocked) {
    console.log('adsBlocked: ' + adsBlocked);
});

 

Hey ūüĎč
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.