How to detect Adblock on my website?
I would like to be able to detect if the user is using adblocking software when they visit my website. If they are using it, I want to display a message asking them to turn it off in order to support the project, like this website does.
If you enter to that site and your browser has some kind of adblock software enabled, then the site instead of showing the actual ads shows a little banner telling the users that the ad revenue is used for hosting the project and they should consider turning Adblock off.
I want to do that on my website, I'm using adsense ads on it, How can I do that?
Solution 1:
My solution is not specific to a certain ad network and is very lightweight. I've been running it in production for a few years. AdBlock blocks all URLs containing the word "ads" or "prebid". So this is what I did:
I added a small js file to my webroot with the name prebid-ads.js
Update 2021-04-12: you might want to call the file prebid-ads.js
or ads-prebid.js
something, because not all ad blockers block files with name like ads.js
anymore.
This is the only line of code in that file
var canRunAds = true;
Then somewhere in my page:
<html>
<head>
<script src="/js/prebid-ads.js"></script>
</head>
<body>
<script>
if( window.canRunAds === undefined ){
// adblocker detected, show fallback
showFallbackImage();
}
</script>
</body>
</html>
Files like ads.js are blocked by at least these adblockers on Chrome:
- AdBlock
- Adblock Plus
- Adblock Pro
- Ghostery
Update on 2019-02-15:
Added Ghostery in the list above because the extension now also blocks requests to ads.js. Very handy. Does this mean that Ghostery is actually helping us devs to detect the blocking of ads with their extension?
Does not work with:
Privacy Badger
Solution 2:
Not a direct answer, but I'd put the message behind the ad to be loaded... rather that trying to detect it, it'd just show up when the ad doesn't.
Solution 3:
async function detectAdBlock() {
let adBlockEnabled = false
const googleAdUrl = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js'
try {
await fetch(new Request(googleAdUrl)).catch(_ => adBlockEnabled = true)
} catch (e) {
adBlockEnabled = true
} finally {
console.log(`AdBlock Enabled: ${adBlockEnabled}`)
}
}
detectAdBlock()