Communicating with iframe host using HTML5 postMessage api

Recently i was working with a client who wanted me to create a widget which was to be embedded on a third party website.

To avoid javascript conflicts with the host and keep the scope of the widget isolated, i had decided to used iframes and it worked out pretty well until there was a new requirement which needed the widgets to communicate with the host website.

I had to create a link on the host website when certain actions would occur in the widget that is within the iframe.

So the prospect of trying to make the iframe communicate with a third party host gave me grief for a while but thanks to my dear old friend Google, I was able to figure out the best way to do it.

Say hello to the  HTML PostMessage API.

Assuming following is the markup for our widget that runs within an iframe and runs on the host webpage.

The postMessage function above takes the data object as first parameter and domain as the second parameter. The domain in this case is set as * so that any domain may listen to the iframe messages if it is setup to do so. 

On the host website i had some javascript that would listen for the event like so:

Notice that postMessage events are names message. There is currently no option to change default event name.

alexey

alexey

Application developer, movie buff, occasional reader and a huge Manchester United fan.
alexey