Skip to content

Instantly share code, notes, and snippets.

@rwestergren
Created August 20, 2016 20:47
Show Gist options
  • Save rwestergren/5d24a086bb8e0f7bd002b98bbf6f6759 to your computer and use it in GitHub Desktop.
Save rwestergren/5d24a086bb8e0f7bd002b98bbf6f6759 to your computer and use it in GitHub Desktop.
A simple closure for detecting AdBlock without additional HTTP requests
/**
* A simple closure for detecting AdBlock without additional HTTP requests
*
* Heavily inspiried by Christian Heilmann's work here: https://www.christianheilmann.com/2015/12/25/detecting-adblock-without-an-extra-http-overhead/
*/
window.adBlockDetect = (function() {
var enabled;
var callback = function(args) {
if (args.length == 1 && typeof args[0] === "function") {
args[0](enabled);
}
};
var poll = function(args) {
if (typeof enabled === "undefined") {
// Wait for check function to complete
setTimeout(function() {
poll(args);
}, 105);
return;
}
// Check completed, do callback
callback(args);
};
(function() {
// Assess adblock usage
var test = document.createElement("div");
test.innerHTML = " ";
test.className = "adsbox";
document.documentElement.appendChild(test);
window.setTimeout(function() {
if (test.offsetHeight === 0) {
enabled = true;
} else {
enabled = false;
}
test.remove();
}, 100);
})();
return function() {
poll(arguments);
};
})();
/**
* Example usage
*/
adBlockDetect(function(r) {
if(r)
{
alert("AdBlocked!");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment