I was working on making Charted embeddable today (coming soon!) which meant I had to brush up on my iframe skills. It’s been three years since we published Third-party JavaScript and Ben gave his talk on seamless iframes, and yet seamless iframes are nowhere to be seen. What happened there?
Luckily for me, I needed only one particular property of seamless iframes, automatic size adjustment, which is pretty easy to implement with cross-window messaging. This means, however, that instead of giving users just an iframe tag to copy you have to give them either two tags (iframe and script) or just a script tag but with config variables. Ugh.
Or maybe not. Behold, an iframe where I replaced the unsupported seamless attribute with some JavaScript nonsense:
If you expand the onload handling code from the iframe it’ll look like this:
First, we grab the iframe and then send a special message (“yo”) together with its ID down to whatever is inside of it. Then we chill while waiting for a reply and once reply is there we check that it was intended for our iframe and then adjust its size accordingly.
Of course, to make it work we’ll need the page inside the iframe to understand the messages we’re sending. It’s not terribly complicated, something along these lines:
I think this code is self-explanatory once you figure out how postMessage API works.
Unfortunately, even though it’d be super nice to give users just one iframe tag to copy, this method has one very serious drawback. Giving people actual JavaScript to copy and not a URL to load means that you won’t be able to do an over-the-air update. You’ll be stuck waiting for people to update their websites and they never do that.
Oh well, iframe and script, sitting in the tree, waiting for seamless iframes to land.