Iframe juggling (how to resize iframe to match content)
You can love or hate iframes, but they have their uses.
I have to use them from time to time, as a last resort. And when i use them, i want the user experience to be the same, as if there were no iframe.
There is a couple of problems with using iframe.
1. Iframe isn't a legal tag in xhtml strict.
2. Iframe height/width doesn't resize to match its content.
3. While navigating inside an iframe, you can't use the browsers back, forward or refresh buttons.
This article is going to try and solve problem 2.
This can only be done with javascript, and is done by measuring the content height, and set the iframe height to the same.
This is where we meat the first problem. Javascript can't access the content inside an iframe. So we need the iframe itself to measure the height.
Next problem is that the content inside the iframe, can't access the iframe itself, so it can't set the iframe height.
The good thing is, that the javascript inside the iframe, can access a javascript function on the page with the iframe.
So we need 1 javascript in the iframe to measure the height, and 1 javascript on the page to set the height.
Next problem is, that this can only be done on the same domain. So if the iframe is on www.mydomain.com and the content in the iframe is on www.myiframedomain.com, the javascript won't work.
This can be fixed with the document.domain property. You need to same top domain, but sub domain can be different, and thus you are able to have iframe content, and page on different servers.
If page is on www.mydomain.com and iframe on iframe.mydomain.com, you need to set document.domain='mydomain.com';
So the javascript inside the iframe would like something like this:
document.domain='mydomain.com'; function getIframeHeight() { var myHeight = document.body.scrollHeight; if (window.parent) { if (window.parent.setIframeHeight) { window.parent.setIframeHeight(myHeight); } } } onload=getIframeHeight;
And the javascript on the page with the iframe:
document.domain='mydomain.com'; function setIframeHeight(myHeight) { document.getElementById("myIframe").height = myHeight; }
Iframe:
<iframe src="http://iframe.mydomain.com/" id="myIframe" frameborder="0"></iframe>