AdBlock detection in JavaScript

By xhuljan 19 January 2021 1K 2

Most of websites are using ads to make profits by visitors.

AdBlock is a browser extension that is used to prevent and hiding ads shown on website.

Many developers are using different plugins on their website to alert their visitors about AdBlock.

In this tutorial I will show you how to detect visitors that use AdBlock in your website with a simple JavaScript code.

Mostly of AdBlock extensions during the page load will search in your HTML and JavaScript code for a list of sites that offer ads and some keywords and will stop them from rendering. So in case they find in your HTML this code:

		<div class="ads-wrapper">
	I am a container for advertisments
</div>
		

AdBlocker will remove it from HTML or it will make it invisible.


Solution

To detect this change we will try to insert in our HTML the code above and later check it if is removed or blocked by AdBlock extension.

The complete code is shown below:

		(function() {
    document.body.innerHTML = document.body.innerHTML + '<div class="ads-wrapper adblock-detect"></div>';
    setTimeout(function() {
        let elm = document.getElementsByClassName("adblock-detect")[0];

        if (!elm || !(elm.offsetWidth > 0 || elm.offsetHeight > 0)) {
            document.dispatchEvent(new Event("adblock-detected"));
        }

    }, 1000);
	
	document.addEventListener("adblock-detected", function() {
		// execute anything if AdBlock is detected
		console.log('AdBlock detected')
	});
})();
		

You can find the complete example here: codepen.io/xhuljan123/pen/GRjXXKP