admin管理员组

文章数量:1334342

I have a problem in my javascript which is just to resize an iFrame based on the content. I have it working in other places but for this one example it is throwing an error. Using the following code the body is null and therefore can't get scrollHeight.

if(document.getElementById('iFrameHelpDesk') != null)
{
    var Height = document.getElementById('iFrameHelpDesk').contentWindow.document.body.scrollHeight;

    document.getElementById('iFrameHelpDesk').height = Height + 40;
}

The html used is:

<iframe src="http://<snipped webaddress>" id="iFrameHelpDesk" scrolling="no" frameborder="no"></iframe>

Why does this not populate the body object?

I have a problem in my javascript which is just to resize an iFrame based on the content. I have it working in other places but for this one example it is throwing an error. Using the following code the body is null and therefore can't get scrollHeight.

if(document.getElementById('iFrameHelpDesk') != null)
{
    var Height = document.getElementById('iFrameHelpDesk').contentWindow.document.body.scrollHeight;

    document.getElementById('iFrameHelpDesk').height = Height + 40;
}

The html used is:

<iframe src="http://<snipped webaddress>" id="iFrameHelpDesk" scrolling="no" frameborder="no"></iframe>

Why does this not populate the body object?

Share Improve this question asked Sep 12, 2012 at 10:05 anothershruberyanothershrubery 21k16 gold badges56 silver badges101 bronze badges 3
  • 1 If the iframe has a different domain to the main page, then you can't access it for security reasons. – grc Commented Sep 12, 2012 at 10:09
  • @grc - The page is on the same domain so does not have this problem. – anothershrubery Commented Sep 12, 2012 at 10:43
  • In addition to my point above, the above code also works for all other iframes that I specify. It's just this one that is causing an issue. – anothershrubery Commented Sep 12, 2012 at 11:07
Add a ment  | 

1 Answer 1

Reset to default 5

Fairly simply I took the code from the document load ($(function() {})) method and put it into it's own method for when the actual iframe loads. Ie.

$('#iFrameHelpDesk').load(function() {

    var Height = document.getElementById('iFrameHelpDesk').contentWindow.document.body.scrollHeight;

    document.getElementById(iFrameHelpDesk').height = Height + 40;

});

This works perfectly, as it should. But it's now confused me as to why some other iframes, which I perform similar code on, are working fine from within the document load. But this works and I'm happy enough with that.

本文标签: javascriptcontentWindowdocumentbody is nullStack Overflow