Front-End iframe Tips and Tricks

Original link: http://caibaojian.com/iframe-adjust-content-height.html

JS adaptive height is essentially setting the height of the iframe so that it equals the height of the embedded webpage, making the scrollbars and signs of nesting invisible. This plays an important role in user experience and website aesthetics.

If the content is fixed, then we can directly define a height for it through CSS, which can also achieve the above requirement. When the content is unknown or changes, there are several different cases.

iframe content unknown, height predictable

At this point, we can add a default CSS min-height value to it, and at the same time use JavaScript to change the height. Common compatibility code includes:


// document.domain = "caibaojian.com";
function setIframeHeight(iframe) {
if (iframe) {
var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;
if (iframeWin.document.body) {
iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;
}
}
};

window.onload = function () {
setIframeHeight(document.getElementById('external-frame'));
};

Demo URL

Demo 1 (If they are under the same top-level domain and different subdomains need to communicate, set document.domain=”caibaojian.com”·

You only need to modify the iframe ID above. Or you can write the code directly inside the iframe. Generally, to avoid polluting the HTML code, we recommend using the code above.

<iframe src="backtop.html" frameborder="0" scrolling="no" id="external-frame" onload="setIframeHeight(this)"></iframe>

Demo 2

When there are multiple iframes

<script language="javascript">
//Enter the list of iframe names whose height you want to automatically adjust based on the page height
//Separate each iframe ID with a comma. For example: ["myframe1", "myframe2"]. If there is only one frame, no comma is needed.
//Define the iframe IDs
var iframeids=["test"];
//Whether to hide the iframe if the user's browser does not support iframe; yes means hide, no means do not hide
var iframehide="yes";
function dyniframesize()
{
var dyniframe=new Array()
for (i=0; i<iframeids.length; i++)
{
if (document.getElementById)
{
//Automatically adjust iframe height
dyniframe[dyniframe.length] = document.getElementById(iframeids[i]);
if (dyniframe[i] && !window.opera)
{
dyniframe[i].style.display="block";
if (dyniframe[i].contentDocument && dyniframe[i].contentDocument.body.offsetHeight) //If the user's browser is NetScape
dyniframe[i].height = dyniframe[i].contentDocument.body.offsetHeight;
else if (dyniframe[i].Document && dyniframe[i].Document.body.scrollHeight) //If the user's browser is IE
dyniframe[i].height = dyniframe[i].Document.body.scrollHeight;
}
}
//Handle display issues for browsers that do not support iframe according to the specified parameter
if ((document.all || document.getElementById) && iframehide=="no")
{
var tempobj=document.all? document.all[iframeids[i]] : document.getElementById(iframeids[i]);
tempobj.style.display="block";
}
}
}
if (window.addEventListener)
window.addEventListener("load", dyniframesize, false);
else if (window.attachEvent)
window.attachEvent("onload", dyniframesize);
else
window.onload=dyniframesize;
</script>

Demo 3

Call by known iframe ID

function iframeAutoFit(iframeObj){
setTimeout(function(){if(!iframeObj) return;iframeObj.height=(iframeObj.Document?iframeObj.Document.body.scrollHeight:iframeObj.contentDocument.body.offsetHeight);},200)
}

Demo 4

Adaptive iframe height for changing content width

<iframe src="backtop.html" frameborder="0" scrolling="no" id="test" onload="this.height=100"></iframe>
<script type="text/javascript">
function reinitIframe(){
var iframe = document.getElementById("test");
try{
var bHeight = iframe.contentWindow.document.body.scrollHeight;
var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
var height = Math.max(bHeight, dHeight);
iframe.height = height;
console.log(height);
}catch (ex){}
}
window.setInterval("reinitIframe()", 200);
</script>

Demo Five

Open the debugging runtime window to see it in action.

Cross-domain iframe adaptive height

In cross-domain situations, due to JavaScript’s same-origin policy, the JavaScript in the parent page cannot get the height of the iframe page. A separate page is needed to act as a proxy.
The method is as follows: suppose a page a.html under www.a.com needs to include a page c.html under www.b.com.
We use another page under www.a.com, agent.html, as a proxy to obtain the height of the iframe page and set the height of the iframe element.

a.html includes an iframe:

<iframe src="http://www.b.com/c.html" id="Iframe" frameborder="0" scrolling="no" style="border:0px;"></iframe>

Add the following code to c.html:

<iframe id="c_iframe"  height="0" width="0"  src="http://www.a.com/agent.html" style="display:none" ></iframe>
<script type="text/javascript">
(function autoHeight(){
var b_width = Math.max(document.body.scrollWidth,document.body.clientWidth);
var b_height = Math.max(document.body.scrollHeight,document.body.clientHeight);
var c_iframe = document.getElementById("c_iframe");
c_iframe.src = c_iframe.src + "#" + b_width + "|" + b_height;  // Pass the width and height of b.htm here via hash
})();
</script>

Finally, put this piece of JS into agent.html:

//code from http://caibaojian.com/iframe-adjust-content-height.html
<script type="text/javascript">
var b_iframe = window.parent.parent.document.getElementById("Iframe");
var hash_url = window.location.hash;
if(hash_url.indexOf("#")>=0){
var hash_width = hash_url.split("#")[1].split("|")[0]+"px";
var hash_height = hash_url.split("#")[1].split("|")[1]+"px";
b_iframe.style.width = hash_width;
b_iframe.style.height = hash_height;
}
</script>

agent.html gets the width and height values from the URL and sets the iframe’s height and width (because agent.html is under www.a.com, it is not restricted by JavaScript‘s same-origin policy when operating on a.html)

Demo Six

Source: Front-end Development Blog

Leave a Comment

Your email address will not be published. Required fields are marked *

中文 EN
🚀

RedGate VPN

免费节点太挤太慢?
升级高速稳定专线

立即体验 →

告别卡顿

RedGate VPN
全球高速节点

免费下载 →
Scroll to Top