How to Detect an AdBlocker in JavaScript

Published May 10, 2020  ∙  Updated May 2, 2022

Method 1: Blocking Scripts

AdBlockers generally work by blocking scripts with the word ads in the name of the script. For instance, ads.js is a fairly common name for scripts that serve ads, so it’s on almost every block list.

This means that a variable we define inside a script called ads.js will be undefined under an AdBlocker since the script will not have been loaded.

// ads.js
let ad = true;

In another script, we can check for the existence of this variable ad.

// custom.js
if( === undefined) {
  // AdBlocker detected!

We can then add these scripts into our project.

We would want to place ads.js within our <head> tag and custom.js at the end of the <body> tag in order to give the AdBlocker time to block ads.

<head><script src="ads.js"></script></head>
<body><script src="custom.js"></script></body>

This is a fairly common technique, but it seems to be a bit wasteful since we have to make a request for another script.

Method 2: Blocking DOM Elements

We can circumvent this issue by understanding that AdBlockers also block some DOM elements with the word ads in the class or id of the element. A common one is adsbox (defined as a removable element by AdBlock Plus).

With this information, we can create a <div> with class adsbox inside JavaScript.

// Create element
let ad = document.createElement('div');
ad.className      = 'adsbox';   = '2px'; = 'absolute';

// Check for ad blocker
let hasAdBlock;
window.setTimeout(function() {
  hasAdBlock = ad.offsetHeight === 0;
}, 100);

We gave it some fixed height (2px) as well as absolute positioning, which will ensure that the element doesn’t mess with the actual layout of the page.

After we create the element, we wait 100ms. It’s long enough for the AdBlocker to do its work, but not long enough for us to notice.

We’ll then check for the height of the element. If there were an AdBlocker, this element would not exist and would have no height.

After all this, we have access to hasAdBlock, which will allow us to do whatever we want with the ad space.

if(hasAdblock) {
  // Show some fallback ad or promotion or random image