connection ceremony for iframe postMessage communications

Recently I've been working with iframe messaging. The postMessage
solution has a lot of advantages and good traction across iframes,
WebWorkers, and browser extensions, with lots of overlap with Web

However the technology has two significant problems.  First is the
"contentWindow that is not a window" confusion I discussed recently.
Second concerns the connection setup. I describe the second problem

The basic communications solution is simple enough:
  window.addEventListener('message', handler, false);  // I'm listening!
  portToOtherWindow.postMessage(message);  // I'm talking to you!

However the solution has two significant problems:
  1. There is no way to know if portToOtherWindow is connected before
you issue postMessage()
  2. All iframes send messages to the same "handler".

The first problem arises because web apps are increasingly
asynchronous for load performance and other reasons.

This leads developers to look for events that will tell them about
'load' on iframes, and that leads them to try
iframe.contentWindow.addEventListener(). It works fine for same-domain
iframes, but fails for cross-domain.

The second problem arises because the handler is attached to the
window and not to an object related to the connection between the two

To workaround for these problems developers have to
  1. create a handshake message sequence, AND
  2. de-multiplex messages.
  3. No use cross-domain iframes

Notice that if multiple developers each create different a handshake
and de-multiplexing solutions, then we end up with isolated
collections of compatible iframes or we end up with
handshake-detection code in iframes.

To leverage an iframe component, a Web page needs to solve two hard
problems: 1) understand the API the component needs and 2) understand
the connection ceremony. The first part is fundamental to using the
component. The second part is just busy work.

I think we should have a standard solution to the connection problem
for cross-domain iframes.

Note that this problem is not shared by other uses of postMessage:
  1. WebWorkers uses port
  2. WebSockets: server always starts first, object is connection not window
  2. MessageChannel: object is connection not window.



Received on Thursday, 9 February 2012 18:15:55 UTC