简体   繁体   中英

How to know that google adsense ad is loaded with JavaScript

I need to know that my google adsense ad (in div id="bottomAd") is loaded.

I tried to wait 5 sec, parse div, and get all "a":

function OnBodyLoad() {
    setTimeout(function () {
        var bottomAd = document.getElementById("bottomAd");
        var linkArray = bottomAd.getElementsByTagName("a");//it's always empty
    }, 5000);
}

It's now working.

Adsense load with iframe that has their own body. So that how to get all "a" element? Or other way to know that adsense ad is loaded?

I can't load iframe content because of private policy (prevented XSS attack). So next code doesn't wokrs:

var array = new Array();
findIframeLinks(bottomAd, "a", array);

...

function findIframeLinks(element, returnElementTagName, array) {
    array.push(element.getElementsByTagName(returnElementTagName));
    var innerIframes = element.getElementsByTagName("iframe");
    for (var i = 0; i < innerIframes.length; i++) {
        if (innerIframes[i].contentDocument) {
            var body = innerIframes[i].contentDocument.getElementsByTagName('body')[0];
            findIframeLinks(body, returnElementTagName, array);
        }

    }
}

I have never used google adsense before but I suspect there will be some events you can subscribe to tell whether something has occur or not.

I did some research on your behalf and found this documentation to be particularly useful, I think the event you are looking for is the ADS_LOADED event. Just do a ctrl - f find on the link for 'ADS_LOADED' https://support.google.com/adsense/answer/1705827?hl=en

Here is the sample code suggested by the doc.

adsLoader.addEventListener(AdsLoadedEvent.ADS_LOADED, onAdsLoaded);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM