Iframe resizing across subdomains
A few weeks back I had a problem: an application I’d installed on a subdomain of interalia.net, which is the domain name of the company I work for, was going to be contained inside an iframe in another application, which happened to be on a different subdomain of the interalia.net domain, and the requirement was that the iframe had to be dynamically resized to fit its contents.
Due to browser security restrictions it’s not allowed to access the properties of a document from a different domain, but fortunately, I found a little trick to work around this issue, it consists on setting both the containing and the contained page to the same base domain, in this case ‘interalia.net’. Like this:
<script type="text/javascript">document.domain = 'interalia.net';</script>
The only condition here is that both applications must live inside a common base domain.
Then, just add the necessary JavaScript code to resize the iframe to the containing page:
<script type="text/javascript"> function resize(iframe) { iframe.height = iframe.contentWindow.document.body.scrollHeight + 30; } </script>
We also have to add the onload attribute to the iframe tag, so our function gets triggered as soon as the inner page is loaded:
<iframe onload="resize(this);" ... />
very interesting.
I’ve implemented a generic solution for this kind of problem: http://www.amirharel.com/2009/07/28/implementing-iframe-toolbar/
Cheers.
Amir
Here’s a little more global and xhtml friendly rewrite of you js (no need to add onload in the html and it executes in its own anon local scope:
(function iframeResize() {
var iframe = document.getElementById('forum');
function resize() {
iframe.height = iframe.contentWindow.document.body.scrollHeight + 30;
}
iframe.onload = resize;
})(); //exec immediately