Communicating between iframes with window.postMessage

Since the late-90s, extensively using iframes has been maligned by webdesingers. Used in the improper way, they make it very hard to save application state, are often ignored by search engines, and open up security issues. It also used to be the case that all kinds of hacking had to go on just to get different frames to talk to each other.

With HTML 5, that isn't really the case anymore. It offers the window.postMessage function to facilitate communication between frames. While I am not holding my breath for a resurgence of this 90s craze, it does open up some new possibilities for iframes.

Below is a quick proof of concept I whipped up. It is two text boxes, one being in a child frame (src: jsfiddle) and the other in the parent window. They both have event listeners waiting for message event that gets generated when you call postMessage.

I ran into a small roadblock when decided how to propagate the message back up to the parent from from within the child frame. You can get the reference to the child's window object by doing a document.querySelector but that isn't there isn't a way to get the parent document from within a child frame. You do get a reference to the caller from event.source though. So once the parent calls the child, you can save this reference and use it later.

Bret Lowrey

Code is like a war - the best code is one never written.

Florida, USA