One of the unspoken rules of the internet is that most content is “free”… at the cost of webpage being littered with advertisements and trackers. This was’t a big problem in the early internet days but trackers and advertisements have become so intrusive and unapologetically aggressive that you almost need to use an ad blocker browser extension.
Ad Blocker Plus is hugely popular and a browser like Brave boasts about being centered around ad blocking. Oftentimes I’ll go to a site and see a modal as me to disable my ad blocker, which got me to thinking about the best way to detect an ad blocker. After a variety of tests and experimentation, I found a really simple way to detect an ad blocker!
// Determines if the user is likely using an ad block extension async function checkAdBlocker() // Used to cache the result let isBlocked; async function tryRequest() try return fetch( new Request("https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js", method: 'HEAD', mode: 'no-cors' )) .then(function(response) // Google Ads request succeeded, so likely no ad blocker isBlocked = false; return isBlocked; ).catch(function(e) // Request failed, likely due to ad blocker isBlocked = true; return isBlocked; ); catch (error) // fetch API error; possible fetch not supported (old browser) // Marking as a blocker since there was an error and so // we can prevent continued requests when this function is run console.log(error); isBlocked = true; return isBlocked; return isBlocked !== undefined ? isBlocked : await tryRequest(); // Using the ad block checker const usingBlocker = await checkAdBlocker();
The logic behind this is as follows:
- Google’s ad file,
adsbygoogle.js, is the perfect sample file, because it is considered enemy number 1 — the first file an ad blocker would want to block due to Google’s ad service popularity
- The file is also paramount to Google’s business so 99.999999999% uptime is practically guarateed
- There’s little chance a network issue would come into play; false positives may come from network connectivity issues or a bad service worker
- If you don’t consider
adsbygoogle.jsyour best sample file, you can easily switching it out for any other URL
From a content creator perspective, a
navigator property that would let you know if an ad blocker was employed would be ideal…but that isn’t happening anytime soon (…never, really). Using simple snippets like this, however, provide a reasonable hint toward the user enabling an ad blocker!
The post How to Detect an Ad Blocker appeared first on David Walsh Blog.