Languages
[Edit]
EN

JavaScript - how to detect if adblock is enabled?

6 points
Created by:
JustMike
26120

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);
});

 

Native Advertising
50 000 ad impressions - 449$
ūüöÄ
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

‚̧ԳŹūüíĽ ūüôā

Join