How to programmatically collapse space in empty div when google ad does not show
Asked Answered
D

5

11

Is there any way to programmatically collapse the empty space that results when a google ad does not show? If so, I would love to see an illustrative example of the same.

Searching around has led me to this official Google resource for accomplishing exactly what I've asked. However, that pertains to Doubleclick for Publishers, which is unfortunately a separate product. I'm pining to know how to handle this for AdSense - some of my users are staring at empty spaces at the moment.


In case it matters, here's an example ad snippet provided by Google AdSense (which I've center-aligned):

    <div style="text-align:center">
        <ins class="adsbygoogle"
             style="display:block"
             data-ad-client="ca-pub-0000000000000000"
             data-ad-slot="0044031319"
             data-ad-format="auto"></ins>
        <script>
        (adsbygoogle = window.adsbygoogle || []).push({});
        </script>
    </div>
Duclos answered 5/4, 2018 at 16:45 Comment(2)
What, technically-speaking, do you mean by "when a google add does not show"?Relative
@TimGrant: Ad inventory doesn't always fill, so for users who find themselves in the said situation, there's a blank white space they have to contend with. Note that this blank space pushes away other divs on the page.Duclos
P
7

But now it is very simple, just insert this CSS;

<style>
ins[data-ad-status=unfilled] {display:none!important}
</style>
Pickerel answered 3/6, 2021 at 3:12 Comment(0)
B
5

I know this is old, but since I've been dealing with this now. A simple enough way to do this in jQuery is to check for all elements with the class adsbygoogle that have no child inside.

This selects all the elements with that class and hides them, effectively collapsing them.

$(".adsbygoogle:empty").hide();

You can do a lot of other stuff with it too, like if it's in a div and you need to hide that too, use the $(".adsbygoogle:empty").parent().hide() to collapse it further.

I'm sure this can be done with vanilla javascript as easily. I suggest to run this line of code after the DOM has loaded and even wait like 10 seconds just to see if google populates the ads.

Bryology answered 29/8, 2019 at 14:25 Comment(7)
I guess worth a nod. Upvoting this (and welcome to the community Dan)Duclos
This is a nice solution, Dan, probably many people will be searching for this also now that Adsense removed their backup ads option. But IMO loading the code just on window load should be sufficient, why do you say to also wait 10 seconds? That could mess with the user experience because of stuff collapsing around while scrolling the page.Legumin
@Legumin You certainly don't have to make it 10 second wait. I put a few second lag because I wasn't sure if adsense is pushing ads right away. But it seems like that happens as soon as the adsbygoogle script loads. So, there's no need to wait in that case.Bryology
I tried this and it resulted in all ads being hidden, on review of response in ad div: <!--No ad requested because of display:none on the adsbygoogle tag-->Pneumonic
It shouldn't hide all ads, it would only hide ads that have nothing in them. If adsbygoogle is not populating your ads with child elements, then its most likely a implementation problem or problem from google side not serving ads or still gauging your site. Also, remember, you need to run this script after adsbygoogle has gone through all of your ads, I usually run it at the end when adsbygoogle has loaded and I have pushed the empty object in all of them. This ensures that I'm not hiding any legit ads.Bryology
This is not a correct solution. adsbygoogle ins element will always have children if ad code implemented correctly. Currently there is no good way to detect whether ad slot was filled with an ad or not. Because AdSense js creates an iframe that loads ad. If google servers didn't find an ad - the iframe will be have empty content. But it's impossible to check for that from outside of the iframe.Kathleenkathlene
@Mikita Belahlazau Yes, there is. The solution offered by nemdub works perfect atm and should be the accepted answer.Legumin
T
3

I noticed that the AdSense code broadcasts a MessageEvent, so when I get a resize-me type event, with 'r_nh': 0 key/value pair, I hide the AdSense container (CSS class adsense-ad) manually.

If you have multiple AdSense containers on the same page, you could try to also parse the qid key from the same message.

window.addEventListener("message", (event)=>{
    try {
        let message = JSON.parse(event.data);
        if (message.msg_type === 'resize-me') {
            let shouldCollapseAd = false;

            for (let index in message.key_value) {
                let key = message.key_value[index].key;
                let value = message.key_value[index].value;

                if (key === 'r_nh' && value === '0') {
                    shouldCollapseAd = true;
                }
            }

            if (shouldCollapseAd) {
                $('.adsense-ad').hide();
            }
        }
    } catch (e) {

    }
});
Tris answered 11/3, 2020 at 21:42 Comment(1)
If you need this to work with multiple ad units: The "qid" key (query id) is of help, but it's not a fixed identifier for the unit as it changes for all the page views, so you can't directly identify the ad unit by it. You need to do extra digging in the DOM for the iframe containing this qid in the "data-google-query-id" param. You can just add an if (key == 'qid') {query_id=value;} in the loop and then something like var ad_to_backup=jQuery('iframe[data-google-query-id="'+query_id+'"]'); if (shouldCollapseAd) {jQuery(ad_to_backup).closest("div").replaceWith( "<p>Your ad code here</p>" );}Legumin
D
1

The link provided which refers to DFP Premium at this point redirects to documentation for Google Ad Manager, so it's possible this feature is available without DFP Premium at this point.


Aside from that...
Usually the existence of an iframe element where you expect it is enough to know whether an ad was put where you were expecting one to be put, or not, in my experience.

setTimeout(function () {
    if (!document.querySelector('#adcontainer').querySelectorAll('iframe').length > 0) {
        document.querySelector('#adcontainer').remove();
    }
},1000*2);

As to whether something useful was loaded into that iframe—that isn't something Google is concerned with, so good luck, you'll need it.

Dillydally answered 10/1, 2019 at 19:28 Comment(3)
Will this violate any of Google's Adsense policies? They are huge on policies and rules and regulations but it boggles the mind to why they simply just don't care when blank ads break web site layouts because it is not collapsing...Billingsgate
@gwpr Not that I'm aware of, but I have limited interest. An ad without a frame with few exceptions has absolutely not loaded. It may have had its impression counted, but if it's not visible, making it further not visible is irrelevant. Google Ads suck. Google sucks. Programmatic ads suck. It isn't even easier, it's more complicated, and simultaneously diminishes a site's quality and gives Google more power over your business.Dillydally
As pathetic as it is, the only way to know for sure an ad has rendered is to visually analyze the viewport for pixels that suggest visual content other than what would be there if empty. The only way to know for sure an ad has been able to be seen is to do the former but additionally with awareness of the scroll position.Dillydally
H
-1

I tried to solve it with CSS as Adsense injects various iframe,ins, and divs with various properties.

This code will collapse whitespace but when you ad is in text, it will overflow some of the text, so inline this needs modification:

<style>
    iframe { height: auto !important}
    ins { height: auto !important}
    #google_ads_frame1 { height: auto !important}
    .adsbygoogle, #aswift_0_expand, #aswift_0_anchor { height: auto!important} /* there might be more of those */
</style>
Heteronomy answered 26/2, 2019 at 3:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.