I’ve been playing around with postMessage just to have a better understanding of how it works, with the following example:
http://hashcollision.org/tmp/hello-iframe.html
It’s slightly elaborate: for each character in the message, this constructs an iframe sourced to http://hashcollision.org/tmp/hello-iframe-inner.html. I then use postMessage to communicate to each individual iframe, telling it what character to show. Also, the iframes communicate the geometry of the iframe back to the parent page via postMessage too. It’s all quite useless, but it’s a cute test page.
One of the things that’s currently awkward is, given the window of an iframe, to find the owning iframe.
I’m doing a for loop to walk all my iframes and check the window with ===, but that seems a bit silly. Are there better ways to do this?
The best solution I can come up with is this: generate a random identifier for each iframe. On all communication between the iframe and the parent window, the iframe will include its “self” identifier in the content of a postMessage. This allows quick-and-easy lookup by the parent when it receives messages.
Here’s the amended example, with hello-iframe.html‘s content as:
and hello-iframe-inner.html‘s content as: