Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 - Cross Browser Iframe postmessage - parent to child communication

I wrote a content script that injects an iframe to any website (therefore different domain).

I need the parent website to send some information to the child iframe, however I couldn't find a way to do it.

The code

var targetFrame = $('#myIframe')[0];
targetFrame.contentWindow.postMessage('the message', '*');

Doesn't work somehow and i get a Cannot call method 'postMessage' of undefined error. But then when I tried the same code directly in Chrome's console, it worked.

I had no trouble sending a postMessage from the child to the parent though but just need a way for the parent to send messages to the child iframe.

like image 924
Draco Avatar asked Aug 02 '12 14:08

Draco


2 Answers

I recently wrote code that did postMessage to an iframe and I encountered quite a similar issue where it said contentWindow is undefined.

In my case, my iframe was not yet part of the DOM tree, it was a variable created by document.createElement('iframe').

Once I put it hidden (width and height 0px, visibility hidden) into the body of the page, contentWindow was no longer undefined and everything worked as expected.

I found the Mozilla Developer Network page for postMessage extremely useful when I was working on my project.

like image 143
Turnerj Avatar answered Sep 24 '22 03:09

Turnerj


I've had success using the following library:

http://easyxdm.net/wp/

It doesn't require any flash/silverlight, only javascript. And it is compatible as far back as as IE6.

It took a little doing to get it up and running, but once it was things ran very smoothly.

Keep in mind that if the iFrame you're opening on the other domain uses a different protocol (HTTP vs. HTTPS) the browser will kick out a warning which prevents your script from running (unless the user says they will accept the risk). If you have access to both protocols it may be wise to host the contents of the iFrame on both HTTP and HTTPS and load the appropriate script accordingly.

Good luck!

like image 28
Tyler Biscoe Avatar answered Sep 22 '22 03:09

Tyler Biscoe