Detect AdBlock and display a message

10

What I'm trying to do is to detect Adblock Plus and display a message.

    
asked by anonymous 20.09.2015 / 09:35

1 answer

21

There is a plugin for this called BlockAdBlock (or FuckAdBlock ), it is supported by the following browsers:

  • Google Chrome
  • Mozilla Firefox
  • Internet Explorer (8+)
  • Safari
  • Opera

Installation

You can manually install by downloading link or:

  • Bower:

    bower install blockadblock
    
  • Node.js / io.js:

    npm install blockadblock
    

Example usage:

<script src="blockAdBlock.js"></script>
<script>
(function() {
    //Se não detectar o adblock
    function adBlockNotDetected() {
        alert('AdBlock não está ativado');
    }

    //Se detectar o adblock
    function adBlockDetected() {
        alert('AdBlock está ativado');
    }

    if(typeof blockAdBlock=== 'undefined') {
        alert("blockAdBlock não foi carregado");
    } else {
        blockAdBlock.onDetected(adBlockDetected);
        blockAdBlock.onNotDetected(adBlockNotDetected);
        blockAdBlock.on(true, adBlockDetected);
        blockAdBlock.on(false, adBlockNotDetected);
        blockAdBlock.on(true, adBlockDetected).onNotDetected(adBlockNotDetected);
    }

    blockAdBlock.setOption('checkOnLoad', false);

    blockAdBlock.setOption({
        debug: true,
        checkOnLoad: false,
        resetOnEnd: false
    });
})();
</script>

Alternative

However, not everything is guaranteed, adblocks evolve and this can be difficult, a simple thing to do is to use the event onerror

<script>
function possivelAdblockDetectado () {
    alert("Possível adblock detectado");
}
</script>

<script onerror="possivelAdblockDetectado()" async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
    style="display:inline-block;width:300px;height:250px"
    data-ad-client="ca-pub-xxxxxxxxxxxxxxxx"
    data-ad-slot="6440411535"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

Or use window.addEventListener (does not work with window.onerror )

<script type="text/javascript">
(function () {
    var
        removeProtocol = /^[a-z]+[:]/i,
        items = [
            "//www.google-analytics.com/analytics.js",
            "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"
        ];

    function detectAdBlock(src) {
        if (items.indexOf(src.replace(removeProtocol, "")) !== -1) {
            alert("Possivel adblock");
        }
    }

    window.addEventListener('error', function(e) {
        if (e.target && e.target.src) {
            detectAdBlock(e.target.src);
        }
    }, true);
})();
</script>
    
20.09.2015 / 20:44