Using analytics tools to measure the impact of your application is part of every website these days.
But measuring how many of your users block your analytics is probably even more important.
And luckily, it’s not that difficult to figure it out.
How it works
In a nutshell - you need to add a fake advertisement div to your website and check if it is visible or not.
In practice:
- Add an empty
div
that’s positioned in the top right corner of your website. That way, it won’t bother users who don’t use AdBlock. - Preferably also add
aria-hidden="true"
to not show this fake ad to users who use accessibility tools. - Once the page is loaded, check whether this fake advertisement div is visible or not.
<div class="ad-box" style="position:fixed;top:0;left:0;" aria-hidden="true">
</div>
<script>
setTimeout(function () {
var adBoxEl = document.querySelector(".ad-box")
var hasAdBlock = window.getComputedStyle(adBoxEl)?.display === "none"
// ... save to DB
}, 2000)
</script>
The way most AdBlocks work these days is that they target specific CSS classes (like class="ad-box"
) and apply display: none
on it. That way, the Ad disappears in your browser.
Always double-check that you don’t break the experience for users that do not use AdBlock.
You can see all the CSS classes that are used for blocking in EasyList blocklist.
Top comments (8)
setTimeout(function() {
fetch('https://www3.doubleclick.net', {
method: "HEAD",
mode: "no-cors",
cache: "no-store",
}).catch(()=>{
alert("detect AdBlock")
});
}, 3500);
it usually works
I have tested different solution. Some old solutions stopped working - AD Blocks are able to go around detection.
I recommend this approach: dirask.com/posts/JavaScript-detect...
The solution works with:
Just don’t go to the dark side of the corresponding un-adBlocking popups using this power please
Why using computed style? Is it possible to set display none and it's visible?
computed style is the "final" style applied. You could have 20 css rules targeting the same elements plus javascript modifying it after that too. Computed gives you the final applied styling.
Yes I understand but if you requests the real node in the DOM itself, means the JavaScript object it should say the same or am I wrong? So no need to use getComputedStyle from window.
I did not want to know what style is applied, I want to no the actual style and that counts.
i believe that is correct, i was just answering your question :)
Thanks! Definitely have to try this out. 👀