In this post we will look at how we can detect if user has installed Adblock extension or not. Websites that depend on ads for revenue can detect adblock and than stop users from viewing their site. So only those users can view your website who don’t have adblock installed.
View Demo
Its important to understand how adblock works before we find a way to detect presence of adblock.
How does Adblock work?
Adblock uses three simple mechanisms to block ads. Mechanisms are Blocking Requests, Element Hiding and Filters. Now we will look at each of them.
Adblock uses source URL of images, iframes, scripts and flash files to identify advertisements in the page. And then it blocks(HTTP and HTTPS requests) and hides(CSS display, visibility and height) those advertisements. It identifies the domain names of advertising networks and also uses build in filters and keywords to identify advertising links.
Adblock identifies text ads using a list of keywords and hides the advertising text using CSS.
Filters allows users to specify new domain names, words and other things to be blocked by Adblock.
Logic To Detect Adblock
We can simply include iframes, images and scripts on our webpage and then point them to advertising networks or embed advertising specific keywords in the URLs. And then detect if resource is been hidden or not. If the elements are hidden then we can be sure that Adblock is installed and running in user browser.
{
//create a iframe. Append the iframe to the body. And then after 100ms check if their offsetHeight, display or visibility is set such a way that user cannot see them.
//In the URL use the words specific to advertising so that Adblock can do string matching.
var iframe = document.createElement("iframe");
iframe.height = "1px";
iframe.width = "1px";
iframe.id = "ads-text-iframe";
iframe.src = "http://domain.com/ads.html";
document.body.appendChild(iframe);
setTimeout(function()
{
var iframe = document.getElementById("ads-text-iframe");
if(iframe.style.display == "none" || iframe.style.display == "hidden" || iframe.style.visibility == "hidden" || iframe.offsetHeight == 0)
{
alert("Adblock is blocking ads on this page");
iframe.remove();
}
else
{
alert("Adblock is not detecting ads on this page");
iframe.remove();
}
}, 100);
}
We check for visibility after 100ms because we need to gives some time to Adblock to intercept the request and also apply its invisibility styling to the iframe. This is a simple way of detecting if Adblock is present or not.
Conclusion
I would recommend you to detect for Adblock and stop Adblock users from accessing your website if your website is completely dependent on advertising revenue. Thanks for reading.