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

前端 未结 4 803
攒了一身酷
攒了一身酷 2021-02-14 12:45

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.

<
4条回答
  •  隐瞒了意图╮
    2021-02-14 13:35

    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) {
    
        }
    });
    

提交回复
热议问题