How can I detect if my AdSense ad is blocked?

Igor Jerosimić picture Igor Jerosimić · Feb 19, 2011 · Viewed 7.5k times · Source

If user has some kind of ad blocker installed, ad blocker will of course remove all ads from my website, and it leaves empty spaces where the ads used to be. I would like to use that empty space by putting some other content in it, like links to most important pages of my website, to do that I need to detect if AdSense javascript is loaded.

Methods that I have tried so far:

if (!document.getElementById("google_ads_frame1"))
{
}

and:

if (typeof(window.google_render_ad) == "undefined")
{
}

Both of those seem to fail in certain situation, for example if browser downloads AdSense javascript files a bit slower, it will execute above mentioned code before AdSense code is loaded and I end up hiding ads for users that don't even have ads blocked.

Do you have any suggestions on how could I make sure that my code is run after AdSense? Or some other way of detecting that AdSense scripts are not loaded?

Answer

Troy Morehouse picture Troy Morehouse · Mar 28, 2015

If using the new AdSense code, you can do an easy check, without resorting to content or css checks.

Place your ads as normal in your markup:

<ins class="adsbygoogle" style="display: block;"
   data-ad-client="ca-pub-######"
   data-ad-slot="#######"
   data-ad-format="auto"></ins>
<script>(adsbygoogle = window.adsbygoogle || []).push({});</script>

Then you call the adsense code at the bottom of your page (note do not use the "async" flag when calling the adsbygoogle.js script):

<script src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

Then add this little snippet of code below that:

<script>
if (!adsbygoogle.loaded) {
   // do something to alert the user
}
</script>

AdSense always creates/sets the flag adsbygoogle.loaded to true when the ads are loaded. You could place the check in a setTimeout function to delay the check by a few seconds.