EN
JavaScript - detect if adblock is enabled (tested in 2024)
6 points
In this article, we would like to show how using JavaScript in simple way detect if some adblock is enabled in web broswer.
Note: the article contains solutions proposed and tested at 03:07 AM in 2023-01-01 (It was my New Year scarify for humanity - Root-ssh).
By default there is no any universal API that indicates ads are blocked or not.
There are tricks how test if adblock is not used:
- check if ads scripts are loaded correctly,
example path:https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js
- check if ads elements are mounted correctly in DOM (it requires multicase tests).
Note: many solutions that were working in the past stopped working, so they are not presented in the above solutions, so we focus on proper solutions only.
In this section, you can find solution that works for:
Source code:
xxxxxxxxxx
1
var ADS_URL = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
2
3
function checkAdsBlocked(callback) {
4
var xhr = new XMLHttpRequest();
5
xhr.onreadystatechange = function () {
6
if (xhr.readyState == XMLHttpRequest.DONE) {
7
callback(xhr.status === 0 || xhr.responseURL !== ADS_URL);
8
}
9
};
10
xhr.open('HEAD', ADS_URL, true);
11
xhr.send(null);
12
}
13
14
15
// Usage example:
16
17
checkAdsBlocked(function(adsBlocked) {
18
console.log('ads are blocked: ' + adsBlocked);
19
});
Where truth of:
xhr.status === 0
means AdBlock is used,xhr.responseURL !== ADS_URL
means uBlock Origin is used.
In this section, you can find above solution in ES6+ version.
xxxxxxxxxx
1
const REQUEST_URL = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
2
3
const REQUEST_CONFIG = {
4
method: 'HEAD',
5
mode: 'no-cors'
6
};
7
8
const checkAdsBlocked = (callback) => {
9
fetch(REQUEST_URL, REQUEST_CONFIG)
10
.then((response) => {
11
callback(response.redirected); // ads are blocked if request is redirected
12
}) // (we assume the REQUEST_URL doesn't use redirections)
13
.catch(() => {
14
callback(true); // ads are blocked if request fails
15
}); // (we do not consider connction problems)
16
};
17
18
19
// Usage example:
20
21
checkAdsBlocked((adsBlocked) => {
22
console.log('ads are blocked: ' + adsBlocked);
23
});