HTML5 - Cross Browser Iframe postmessage - parent-child relationship

I wrote a content script that injects an iframe into any site (hence a different domain).

I need a parent website to send some information to a child iframe, however I could not find a way to do this.

The code

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

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

I had nothing to send postMessage from the child to the parent, but I just need the parent to be able to send messages to the child iframe.

+7
source share
3 answers

I recently wrote code that made postMessage in an iframe , and I came across a pretty similar question where it said that 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') .

As soon as I put it hidden (width and height 0px, visibility is hidden) in the body of the page, contentWindow 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.

+2
source

I had success using the following library:

http://easyxdm.net/wp/

It does not require flash / silverlight, only javascript. And it is also compatible with IE6.

It took a little work to get it up and running, but as soon as everything was in order, it went smoothly.

Keep in mind that if the iFrame that you open in another domain uses a different protocol (HTTP versus HTTPS), the browser will issue a warning that prevents your script from running (unless the user says that they will take the risk). If you have access to both protocols, it is advisable to place the contents of the iFrame on both HTTP and HTTPS and load the corresponding script accordingly.

Good luck

0
source

You do not need to specify contentWindow. Try the following:

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

All Articles