Forum Moderators: open
I'm attempting to dynamically adjust the size of an iframe which displays another website. The height would be the height of the document being shown within the iframe.
This works when the iframe is showing pages locally. If you change the local page to a page on another domain that contains the same code, the iframe is no longer dynamically resized.
It seems to me like the parent.setIframeHeight is not being defined correctly. Since the page being shown in the iframe is off-domain, no parent document is present.
---------
Is there a way to define the parent document in this situation?
---------
The following code is placed on the page (off domain) which will be loaded in the iframe:
function goSetHeight() {
if (parent == window) return;
else parent.setIframeHeight('iframe');
}
<body onload="goSetHeight()">
---------
The following code goes in the page on which the iframe is located (local):
function getDocHeight(doc) {
var docHt = 0, sh, oh;
if (doc.height) docHt = doc.height;
else if (doc.body) {
if (doc.body.scrollHeight) docHt = sh = doc.body.scrollHeight;
if (doc.body.offsetHeight) docHt = oh = doc.body.offsetHeight;
if (sh && oh) docHt = Math.max(sh, oh);
}
return docHt;
}
function setIframeHeight(iframeName) {
var iframeWin = window.frames[iframeName];
var iframeEl = document.getElementById? document.getElementById(iframeName): document.all? document.all[iframeName]: null;
if ( iframeEl && iframeWin ) {
iframeEl.style.height = "auto"; // helps resize (for some) if new doc shorter than previous
var docHt = getDocHeight(iframeWin.document);
// need to add to height to be sure it will all show
if (docHt) iframeEl.style.height = docHt + 30 + "px";
}
}
function loadIframe(iframeName, url) {
if ( window.frames[iframeName] ) {
window.frames[iframeName].location = url;
return false;
}
else return true;
}
<iframe name="iframe" src="http://www.someotherdomain.com">