How to detect AdBlock users.

In this guide, we are going to show you how to detect AdBlock users using JavaScript.

To “fight back” and attempt to reclaim lost ad revenue, developers can do one of the following:

  1. Find another revenue stream. Unfortunately, this is not always possible.
  2. Block AdBlock users in the hope that they whitelist your website.
  3. Display a message to AdBlock users and politely ask them to not run the plugin on your domain.

Detecting AdBlock users with JavaScript.

To detect AdBlock, we will need to trick the plugin into thinking that a file on our server is displaying ads.

In other words, we want it to block a particular resource.

For this example, we will create a JavaScript file called ads.js. The name is extremely important, as we want the plugin to believe that the file is serving ads.

Inside this JavaScript file, we will create a variable:

//Our ads.js file
var canRunAds = true;

That’s it. All we need is one simple variable.

We will then include the JavaScript file in our web page like so:

<!--include ads.js-->
<script src="js/ads.js"></script>

If a visitor is using an ad-blocker, then that plugin should block our ads.js file.

If that happens, then the variable “canRunAds” will not exist.

To detect this, we can do the following:

    if( window.canRunAds === undefined ){
        //AdBlock is enabled.
        //The variable canRunAds does not exist.

In the code above, we check to see if the variable from ads.js exists or not.

If the variable “canRunAds” does not exist, then we can presume that an ad-blocking plugin has stopped the file from loading.

At that stage, we can block the user.

There are three ways to do this:

  • Display an overlay that hides the main content.
  • Redirect them to a special page.
  • Remove or hide important elements on the page.

Personally speaking, I would use a transparent overlay to obscure the main content.

You can do this by using the z-index CSS attribute and absolute positioning. There are plenty of online tutorials that will show you how to create HTML overlays.

Displaying a custom message.

If you think that blocking AdBlock users is too harsh, then you can take a more polite approach and remind them to whitelist your domain.

If you want to display a message instead of concealing then content, you can do something like this:

    if( window.canRunAds === undefined ){

In your HTML, you can create a hidden DIV with the ID “special-message”:

<div id="special-message">
    <p>Please disable AdBlock for our website as we rely 
       on advertisements to pay for our hosting.

If the user has Adblock enabled, our code will detect its presence and display the hidden message.