Detect if a user has an adblocker enabled, redirect to another page but only once & display alternative to ads with jQuery

StackOverflow https://stackoverflow.com/questions/20131818

  •  03-08-2022
  •  | 
  •  

Frage

This question has been asked quite a few times, but never exactly like this. What do I want:

  • Check if a user has an adblocker enabled
  • If so, re-direct the user to a landing page
  • On that landing page, display a link that directs the user to the original destination
  • The user will only be directed to that landing page once (or once every x days) as long as the adblocker is enabled
  • Ads (that are hidden) must be replaced by custom HTML

Preferable use of jQuery (client side, because as far as I know it is impossible to detect an adblocker server-side).

Note: I am only concerned with Google Advertisements.

War es hilfreich?

Lösung

Test Information

  • Answer written on 21st of November 2013. Solution may not apply throughout the ages
  • Only tested on Chrome 31 and Firefox 25, on a Windows 8 64 bit machine
  • Improved readability in this JSFiddle.

UPDATE For increased user-friendliness I am not applying this technique on my website anymore.

What You Need

  • jQuery
  • jQuery Cookie
  • A .js file (henceforth called scripts.js) that runs on your site
  • A div wrapper for your advertisements. Don't use classes that are too easy to detect as related to ads! Try something like class="cont-ad". So you wrap each ad individually in a div with that class, e.g. <div class="cont-ad">.
  • A page on which you explain why you need ads on your website. I'll call it ads.html. Give the body-tag of that page a class that is easily identifiable but also unique. (You can use IDs instead, but I find classes easier.) I'll give the body a class on-ads.

Note: only the body tag inside the ads.html page can have this class!

The load order of the first three files should be:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="/js/jquery.cookie.js"></script>
<script src="/js/scripts.js"></script>

All the scripting that I will post now, will go inside scripts.js.

Checking if an Adblocker Is Active

As I said before, we need to check for an adblock client-side, not server-side. This means we cannot use PHP for this. All over the web I found that different adblocks handle blocking the ads differently. Therefore, we need a couple of conditions to see whether an ad has been blocked. I will be using jQuery for this.

Some adblockers hide the ad, some don't allow the ad to load and others just reduce the height to zero. These are the three conditions found below.

if($("ins.adsbygoogle").is(':empty') ||
   $("ins.adsbygoogle").height() === 0 ||
   !$("ins.adsbygoogle").is(":visible")) {

Note that the last condition can also be written as .is(":hidden"). I thought not visible was clearer.

As I said before, these conditions check whether the ads are "blocked" or not. When this returns true, we can do what we want!

Change Content and Add another If-clause

First, we want to display some alternative to the ads that are hidden. We will change the HTML of the wrapper of the ad. This will remove the code for the ad entirely, but that doesn't matter because it is blocked anyway.

$(".cont-ad").html('<span class="adblock-message">Please. Do not take my ads away! <a href="http://www.yoursite.com/ads.html" target="_self" title="Ads">Read more.</a></span>');

But we also want to redirect our user to a landing page, right? But only once. So what we will do is:

  • Check whether a cookie ads_checked exists (I will come back to this in a minute) and if it doesn't, go to our landing page
  • Save the location where the user was headed to in another cookie locational_cookie

In code, it looks like this.

if ($.cookie('ads_checked') == null) {
    // Set cookie with value of current page
    $.cookie('locational_cookie', window.location, {
        expires: 7, // Not really necessary
        path: '/'
    });
    // Redirect
    window.location = "http://www.yoursite.com/ads.html";
}

We only want to replace the ads and only redirect a user when the ads are blocked, so we put all the above in the very first if-clause:

if ($("ins.adsbygoogle").is(':empty') ||
    $("ins.adsbygoogle").height() === 0 ||
    !$("ins.adsbygoogle").is(":visible")) {

    // Change the HTML content of the ad
    $(".cont-ad").html('<span class="adblock-message">Please. Do not take my ads away! <a href="http://www.yoursite.com/ads" target="_self" title="Ads">Read more.</a></span>');

    if ($.cookie('ads_checked') == null) {
        // Set cookie with value of current page
        $.cookie('locational_cookie', window.location, {
            expires: 7, // Not really necessary
            path: '/'
        });

        // Redirect
        window.location = "http://www.yoursite.com/ads.html";
    }
}

There, that's the first big chunk.

Check if on Landing Page, Unset Cookie, Set another and Add Content

The idea of having a ads.html landing page, is that users can look up what your stance on advertisement is and why you need the revenue. This page needs to be accessible without the script we are building. This means that not all content needs to be on that page all the time. For instance, the "back to original destination" button/link that we are going to create, mustn't be there if the user navigated to ads.html in the first place (when the "original destination" would actually be that page itself).

So, we have to add a link "Back to original destination" if a user has been redirected. We can do this by checking for the existence of the cookie we set earlier. Just to be sure, we can also check for the body tag that we provided for that page only, but that isn't really necessary.

if ($("body").hasClass("on-ads") && $.cookie('locational_cookie') != null) {

But what do we need inside this function? First of all, we need to set the href of the "back" link to the original location. We saved the original destination in a cookie, so that's quite useful! After that, we want to remove that cookie (locational_cookie) - we don't need it any more. We need another cookie, though. (Getting hungry yet?)

Recall the previous chunk of code we built earlier: in the embedded if-clause we check for the existence of a cookie called ads_checked. If that cookie does not exist, we want to send the user to the landing page, but we only want to send him there once. So what we do is: when the user is on this landing page, set a cookie - and if that cookie exists, the user cannot be redirect again. Now we create that cookie as well.

Note that we have to append the back link to some HTML element on the ads.html page. Here, it's called #wrapper.

if ($("body").hasClass("on-ads") && $.cookie("locational_cookie") != null) {
    // Append back link
    $("#wrapper").append('<p>Get to your <em><a href="' + $.cookie("locational_cookie") + '" target="_self">original destination</a></em>.</p>');
    // Remove locational cookie
    $.removeCookie('locational_cookie', {path: '/'});

    // Set ads_checked cookie
    $.cookie('ads_checked', 'true', {
        expires: 7, // so the user will be redirected to the landing page again after 7 days
        path: '/'
    });
}

Result

And that's basically it! Everything put together, we get this, in a nice document ready function. Here is the JSFiddle, which might be a little clearer.

$(document).ready(function () {
    if ($("body").hasClass("on-ads") && $.cookie("locational_cookie") != null) {

        // Append back link
        $("#wrapper").append('<p>Get to your <em><a href="' + $.cookie("locational_cookie") + '" target="_self">original destination</a></em>.</p>');

        // Remove locational cookie
        $.removeCookie('locational_cookie', {
            path: '/'
        });

        // Set ads_checked cookie
        $.cookie('ads_checked', 'true', {
            expires: 7, // so the user will be redirected to the landing page again after 7 days
            path: '/'
        });
    }

    if ($("ins.adsbygoogle").is(':empty') || $("ins.adsbygoogle").height() === 0 || !$("ins.adsbygoogle").is(":visible")) {

        // Change the HTML content of the ad
        $(".cont-ad").html('<span class="adblock-message">Please. Do not take my ads away! <a href="http://www.yoursite.com/ads" target="_self" title="Ads">Read more.</a></span>');

        if ($.cookie('ads_checked') == null) {

            // Set cookie with value of current page
            $.cookie('locational_cookie', window.location, {
                expires: 7, // Not really necessary
                path: '/'
            });

            // Redirect
            window.location = "http://www.yoursite.com/ads";
        }
    }
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top