Skip to content

Instantly share code, notes, and snippets.

@boian-ivanov
Last active December 28, 2020 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save boian-ivanov/173b5d2df97c73e93175b6cd6cc9e3ef to your computer and use it in GitHub Desktop.
Save boian-ivanov/173b5d2df97c73e93175b6cd6cc9e3ef to your computer and use it in GitHub Desktop.
Adblock detection based on ad service URL. This implementation for adblock detection is based on a blocked URL. In certain scenarios, adblockers stop element hiding (which generally is used to detect adblockers) and this approach goes around it.
// MutationObserver demo from : https://jsfiddle.net/Xotic750/gZysL/
(function(global){
"use strict";
let adServiceUrl; // ex. Google tag manager, ad sence, fb pixel, etc
if (!("MutationObserver" in global)) {
global.MutationObserver = global.WebKitMutationObserver || global.MozMutationObserver;
}
// random string gen by : https://gist.github.com/6174/6062387
let randomStr = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15),
containerId = "container." + randomStr,
imgId = "img." + randomStr;
// Create an observer instance to execute when mutations are observed
let observer = new MutationObserver(function (mutationsList) {
console.log(mutationsList);
mutationsList.forEach(mutation => {
if(mutation.type == 'childList') {
Array.prototype.forEach.call(mutation.target.children, function(child) {
if (child.id === imgId) {
child.addEventListener('load', function() {
alert("No adblocker detected");
});
child.addEventListener('error', function() {
alert("Adblocker detected");
})
}
});
}
});
});
// create wrapper id
let div = document.createElement('div');
div.id = containerId;
div.style = "width:1px;height:1px;";
document.body.append(div);
let container = document.getElementById(containerId);
// Start observing the target node for configured mutations
observer.observe(container, {
attributes: true,
characterData: true,
childList: true,
subtree: true,
attributeOldValue: true,
characterDataOldValue: true
});
// Add child image with the ad service link
let img = new Image(1, 1);
img.id = imgId;
img.src = adServiceUrl;
container.append(img);
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment