Sometimes, just sometimes, I want to do something completely ludicrous with my web pages. For instance, just recently I wanted to embed dynamic, externally hosted content in a Blogger page, and I wanted to do it without having internal scroll bars. This meant sizing the iframe hosting the content to precisely fit the content within it, resizing it every time the content changed.
Told you it was ludicrous.
Anyway, I quickly ran into a few problems to do with cross-site scripting. Specifically, when a page is contained in an iframe within a page on a different domain, there are two things you can't do:
- It's impossible to size an iframe to its contents from the containing page
- It's impossible to size an iframe to its contents from inside the iframe
So how do I do it? Well, I use a mighty XSS hack! Give this a try:
Create a resizing widget
Create a blogger page called 'resize-widget' that contains the following code:
Of course, it assumes that it is allowed to call functions on the topmost frame (i.e. it's on the same domain), and that the updateIFrame function exists. But assuming that is true, all is well.
Create the containing page
Next, create a page to contain your iframe to be resized. I will call mine iframe-resize-demo, although of course you can call it anything you like. Put this code in it:
Aha! There's that updateIFrame function that takes a height as its parameter! What does it do? It updates the height of the iframe to match the height parameter. Actually it does a little more - it resizes it to the maximum of either the height parameter or the scrollHeight of the Blogger sidebar. It does this to ensure the Blogger template flows properly.
Create the dynamic, externally-hosted content
Of course, the external content can contain anything you like. But put this in it:
What does it do? When the document body loads, it calculates the total height of the document, adds it to the URL of the resize-widget page we created a while back, and loads that URL into the iframe. This sets of a chain of events that culminates with the height parameter calculated here being passed into the updateIFrame function, and the iframe containing the page we've just written being expanded to fit!
Don't you feel dirty now?
Inspiration from Blog What I Made, and modified to work with Blogger.