Search code examples
javascriptjqueryiframegoogle-dfp

Checking if iFrame content exists


I'm working with two if statements in a jQuery each statement that look for an iFrame within the body of an element and sets the height accordingly if it's empty or if it has content. I'm using this to check if DFP has served an advert or if it has served a blank.

What I have is the following:

$('.element-paragraph').each(function(index) {
    var characterCount = $(this).text().length
    totalCount = totalCount + characterCount

    if (totalCount > 1200)  {
        totalCount = 0;
        var feedData = "pos" + adUnit.toString();
        var advertInsert = '<div id=' + feedData +  ' class="inline-ad big-box-300x250 border-bottom-" data-mobile-display="" data-desktop-display="" data-ad-type="' + feedData + '" style=""></div>'
        var ad_script = '<script type="text/javascript">googletag.cmd.push(function() { googletag.display("' + feedData + '"); });</script>';
        $(this).append(advertInsert)
        $(this).append(ad_script);

        adUnit++;

        if ($("#" + feedData).contents().find("iframe").find("body").length > 0) {
            console.log("Advert found for unit" + feedData)
            $("#" + feedData).css("height","350");
        }

        else {
            console.log("Advert not found for unit" + feedData)
            $("#" + feedData).css("height","0");
        }
    }
});

The content is nested like so: #id > iFrame > div > div > #document > html > body

It doesn't seem to be properly checking the length of the body within the iFrame. If I remove the else statement it adjusts the height properly but is doing so for every advert that runs through the loop instead of just the ones it finds content for.


Solution

  • You should use .contents() to reveal iframe document.

    $("#iframe_container").find("iframe").contents().find("body")
    

    In your case:

    $("#" + feedData).find("iframe").contents().find("body").contents().length > 0
    

    because empty iframe does have body