Search code examples
javascriptjqueryadblock

script to detect adblock isn't working


Can someone please help me with this script? It is to detect adblock. I have <script src="/js/ads.js"></script> in the head (a empty ads.js in the folder). Adblock will block this from loading thus not being on the page. Then I have the code below that will detect if the script is loaded or not. For some reason it is not working properly and still displays images. I had someone write the script below as well for it to check for ads 3 times with a 1 second interval but it seems to check infinitely 3 times at once. Can someone please help me work this properly? And also if it detects that it does load properly it won't keep pasting images into the div?

<script>
$(document).ready(function () {
    var count = 3;
    for (var i = 0; i < count; i++) {
        setInterval(function () {
            if (window.canRunAds === undefined) {
                $('#StEQBidTjU').prepend('<img src="/miscimg/mZKoARJXcF.jpg" id="PtZZtkYjaR" />')
                $('#AbHPbbbxyl').prepend('<img src="/miscimg/6hZ4nqcBZd.jpg" id="PLyCMzOHpx" />');
            }
        }, 1000);
    }
});
</script>


Solution

  • You need to keep track of the count in each interval, and clear it once it's ran 3 times.

    $(document).ready(function () {
        var count = 3,
            interval = setInterval(function () {
              if (--count < 0) {
                clearInterval(interval);
              }
              if (window.canRunAds === undefined) {
                $('#StEQBidTjU').prepend('<img src="/miscimg/mZKoARJXcF.jpg" id="PtZZtkYjaR" />')
                $('#AbHPbbbxyl').prepend('<img src="/miscimg/6hZ4nqcBZd.jpg" id="PLyCMzOHpx" />');
              }
            }, 1000);
    });