I wanted to make an iframe
behave like a normal page (I needed to make a fullscreen banner inside an iframe
element), so here is my script:
(function (window, undefined) {
var frame,
lastKnownFrameHeight = 0,
maxFrameLoadedTries = 5,
maxResizeCheckTries = 20;
//Resize iframe on window resize
addEvent(window, 'resize', resizeFrame);
var iframeCheckInterval = window.setInterval(function () {
maxFrameLoadedTries--;
var frames = document.getElementsByTagName('iframe');
if (maxFrameLoadedTries == 0 || frames.length) {
clearInterval(iframeCheckInterval);
frame = frames[0];
addEvent(frame, 'load', resizeFrame);
var resizeCheckInterval = setInterval(function () {
resizeFrame();
maxResizeCheckTries--;
if (maxResizeCheckTries == 0) {
clearInterval(resizeCheckInterval);
}
}, 1000);
resizeFrame();
}
}, 500);
function resizeFrame() {
if (frame) {
var frameHeight = frame.contentWindow.document.body.scrollHeight;
if (frameHeight !== lastKnownFrameHeight) {
lastKnownFrameHeight = frameHeight;
var viewportWidth = document.documentElement.clientWidth;
if (document.compatMode && document.compatMode === 'BackCompat') {
viewportWidth = document.body.clientWidth;
}
frame.setAttribute('width', viewportWidth);
frame.setAttribute('height', lastKnownFrameHeight);
frame.style.width = viewportWidth + 'px';
frame.style.height = frameHeight + 'px';
}
}
}
//--------------------------------------------------------------
// Cross-browser helpers
//--------------------------------------------------------------
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
} else {
elem.attachEvent("on" + event, function () {
return (fn.call(elem, window.event));
});
}
}
})(window);
The functions are self-explanatory and have comments to further explain their purpose.