Getting an accurate height for the iFrame is not as simple as it should be, as you have a choice of six different properties that you can check and none of them give a constantly right answer. The simplest solution I've come up with is this function that works so long as you don't use CSS to overflow the body tag.
function getIFrameHeight(){
function getComputedBodyStyle(prop) {
return parseInt(
document.defaultView.getComputedStyle(document.body, null),
10
);
}
return document.body.offsetHeight +
getComputedBodyStyle('marginTop') +
getComputedBodyStyle('marginBottom');
}
This is the IE9 version, for the much long IE8 version see this answer.
If you do overflow the body and you can't fix your code to stop this, then using either the offsetHeight
or scrollHeight
properties of document.documentElement
are your better options. Both have pros and cons and it best just to test both and see which works for you.
The most reliable method is to workout the position of the bottom of the lowest element on the page. This works great in modern browsers, but is slow in older ones.
function getMaxElement(elements) {
var
elementsLength = elements.length,
elVal = 0,
maxVal = 0;
for (var i = 0; i < elementsLength; i++) {
elVal = elements[i].getBoundingClientRect()[side] + getComputedStyle('marginBottom',elements[i]);
if (elVal > maxVal) {
maxVal = elVal;
}
}
return maxVal;
}
These code snippets come from a library I wrote to keep an iFrame sized to it's content. In addition to this it watches events in both the iFrame and the parent page to ensure the iFrame stays the right size and also provides other functions to solve common iFrame problems. So might be of interest to you.
https://github.com/davidjbradshaw/iframe-resizer