Last active
April 22, 2019 07:54
-
-
Save softwarespot/94f79a066a0592d8439bd6e82454536e to your computer and use it in GitHub Desktop.
Detect if an adblocker exists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Detects if an adblocker exists | |
* | |
* @example | |
* adblockerDetectAsync() | |
* .then(() => console.log('Detected adblocker:', hasAdblocker)) | |
* .catch((err) => console.error('[adblockerDetectAsync]', err)); | |
* | |
* @returns {Promise<boolean>} Returns a Returns a {@link Promise|Promise} that resolves with either true, if an adblocker exists; otherwise, false | |
*/ | |
function adblockerDetectAsync() { | |
return new Promise((resolve) => { | |
// Taken from URL: https://christianheilmann.com/2015/12/25/detecting-adblock-without-an-extra-http-overhead/ | |
const el = document.createElement('div'); | |
el.innerHTML = ' '; | |
// Taken from URL: https://stackoverflow.com/a/34577648 | |
el.classList.add('ads', 'ad', 'adsbox', 'doubleclick', 'ad-placement', 'carbon-ads'); | |
document.body.appendChild(el); | |
setTimeout(() => { | |
const hasAdblocker = el.offsetHeight === 0; | |
// See URL: https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove | |
el.remove(); | |
resolve(hasAdblocker); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment