Detecting AdBlock without an extra HTTP overhead
Friday, December 25th, 2015 at 11:27 amThe other day Cats who code had a blog post about detecting AdBlock, where the main trick is to try to load a JavaScript document with the name adframe.js:
<script type="text/javascript"> var adblock = true; </script> <script type="text/javascript" src="adframe.js"></script> <script type="text/javascript"> if(adblock) { //adblock is installed } </script> |
The adframe.js
document only contains one line unsetting the adblock
Boolean:
var adblock = false; |
This seems to work pretty well (and you can see it used in many web sites), but also seems a bit wasteful having to try another script loading and executing. Of course there are many adblocker detection scripts available (some with colourful names), but I wondered what the easiest way to do that is. The trick described in the abovementioned article using a bsarocks
class on an element stopped working.
Detecting AdBlock without another request
What does work, though is the following and you can see it in action and get the code on GitHub:
var test = document.createElement('div'); test.innerHTML = ' '; test.className = 'adsbox'; document.body.appendChild(test); window.setTimeout(function() { if (test.offsetHeight === 0) { document.body.classList.add('adblock'); } test.remove(); }, 100); |
The trick is the following:
- You create an element with the class
adsbox
(as defined as a removable element in the definition file of AdBlock Plus) - You add it to the document and after a short while you read its
offsetHeight
- If AdBlock is installed, the element won’t have any height.
You can see it in action here:
Ethics?
Play nice with this. I’m not going into the ethics of ad blocking or detecting ad blockers. Fact is, we started an arms race with that nobody can win. The more we block, the more aggressive ads will get. As users we should vote with our voice and tell companies that we hate their aggressive advertising. We should also start to understand that nothing is free. As publishers, we should start thinking that showing ads as our only revenue stream is a doomed way of monetisation unless we play dirty.