I am working on an iGoogle-like application. Content from other applications (on other domains) is shown using iframes.
How do I resize the iframes to fit the height of the iframes’ content?
I’ve tried to decipher the javascript Google uses but it’s obfuscated, and searching the web has been fruitless so far.
Update: Please note that content is loaded from other domains, so the same-origin policy applies.
We had this type of problem, but slightly in reverse to your situation – we were providing the iframed content to sites on other domains, so the same origin policy was also an issue. After many hours spent trawling google, we eventually found a (somewhat..) workable solution, which you may be able to adapt to your needs.
There is a way around the same origin policy, but it requires changes on both the iframed content and the framing page, so if you haven’t the ability to request changes on both sides, this method won’t be very useful to you, i’m afraid.
There’s a browser quirk which allows us to skirt the same origin policy – javascript can communicate either with pages on its own domain, or with pages it has iframed, but never pages in which it is framed, e.g. if you have:
then
home.htmlcan communicate withframed.html(iframed) andhelper.html(same domain).framed.htmlcan send messages tohelper.html(iframed) but nothome.html(child can’t communicate cross-domain with parent).The key here is that
helper.htmlcan receive messages fromframed.html, and can also communicate withhome.html.So essentially, when
framed.htmlloads, it works out its own height, tellshelper.html, which passes the message on tohome.html, which can then resize the iframe in whichframed.htmlsits.The simplest way we found to pass messages from
framed.htmltohelper.htmlwas through a URL argument. To do this,framed.htmlhas an iframe withsrc=''specified. When itsonloadfires, it evaluates its own height, and sets the src of the iframe at this point tohelper.html?height=NThere’s an explanation here of how facebook handle it, which may be slightly clearer than mine above!
Code
In
www.foo.com/home.html, the following javascript code is required (this can be loaded from a .js file on any domain, incidentally..):In
www.bar.net/framed.html:Contents of
www.foo.com/helper.html: