simpleanalytics / roadmap

File you bugs and feature requests here
24 stars 2 forks source link

Detect ad-blockers #645

Open adriaandotcom opened 2 years ago

adriaandotcom commented 2 years ago

For example like this:

var box = document.createElement("div");
box.className = "ads AdSense adpopup adszone adslot AD300";
box.style.height = "1px";
document.body.appendChild(box);

var hasAdblocker = !box.offsetHeight;
console.log({ hasAdblocker });
box.parentNode.removeChild(box);
adriaandotcom commented 2 years ago

Other ways:

var box = document.createElement("div");
box.className = "ads AdSense adpopup adszone adslot AD300";
box.style.height = "1px";

var observer = new MutationObserver(function () {
  if (document.body.contains(box)) {
    console.log("It's in the DOM!");
    observer.disconnect();
    setTimeout(function () {
      var hasAdblocker = !box.offsetHeight;
      console.log({ hasAdblocker });
    }, 0);
  }
});

observer.observe(document.body, {
  attributes: false,
  childList: true,
  characterData: false,
  subtree: true,
});

document.body.appendChild(box);