Skip to content

Instantly share code, notes, and snippets.

@softwarespot
Last active April 22, 2019 07:54
Show Gist options
  • Save softwarespot/94f79a066a0592d8439bd6e82454536e to your computer and use it in GitHub Desktop.
Save softwarespot/94f79a066a0592d8439bd6e82454536e to your computer and use it in GitHub Desktop.
Detect if an adblocker exists
/**
* 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 = '&nbsp;';
// 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