Detecting Advert Blockers with Javascript
I (as many others do) use an ad blocker.
Recently I visited a website that detected I was using an ad blocker and hid the content from me.
Slightly annoying (if not expected) but as I discovered this is simply done with JavaScript and with some quick disabling of the JavaScript I was able to read the article.
Sneaky.
However, it did interest me as to how it was achieved and as it transpires the technique is quite simple.
Firstly create a file called advert.js
In advert.js
:
;var __sneaky_adverts = true;
In your html file then you could have something like;
<!doctype html>
<html>
<body>
<script src="advert.js" async></script>
<script>
window.onload = function(){
if (typeof __sneaky_adverts == 'undefined') {
// content is blocked
}
}
</script>
</body>
</html>
The technique is simple.
Load advert.js. If it does load then __sneaky_adverts will be true (!undefined). If it fails then the if
will fire.
Lovely.
You may ask why I am using a window.onload event though.
Good question.
I advocate speed. I don’t want advert.js to render block so I am loading it asynchronously. That means I have to give the browser enough time to load the file before I check for __sneaky_adverts :)
Like this post? Share it :)