Draco
Draco

Reputation: 262

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.

Upvotes: 8

Views: 6853

Answers (3)

Turnerj
Turnerj

Reputation: 4278

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.

Upvotes: 3

christianbundy
christianbundy

Reputation: 674

You don't need to target contentWindow. Try this:

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

Upvotes: -2

Tyler Biscoe
Tyler Biscoe

Reputation: 2422

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!

Upvotes: 1

Related Questions