How can I do cross-domain postMessage?

The documentation for postMessage implies that cross-domain messaging is possible. But:

// When the popup has fully loaded, if not blocked by a popup blocker 

This is not a very clear point on how to do this.

Imagine two websites:

  • [Parent] is hosted at qc-a.nfshost.com
  • [Baby] posted on qc-b.quadhome.com

In parent:

 document.addEventListener('message', function(e) { alert('Parent got (from ' + e.origin + '): ' + e.data); e.source.postMessage('Round-tripped!', 'http://qc-b.quadhome.com'); }, false); function go() { var w = window.open('http://qc-b.quadhome.com', 'test'); /* This doesn't work because same-origin policy prevents knowing when the opened window is ready. */ w.postMessage('Vain attempt.', 'http://qc-b.quadhome.com'); } 

And, in the child:

 document.addEventListener('message', function(e) { alert('Child got (from ' + e.origin + '): ' + e.data); }, false); window.opener.postMessage('Ready!', 'http://qc-a.nfshost.com'); 

All to no avail.

reference

+7
javascript html5 cross-domain postmessage
source share
2 answers

I currently see two questions. A small error in the code and a problem with the timeout.

1) The error that I see in your code is that you are using document.addEventListener. I think window.addEventListener is correct. It is in the example on the postMessage page.

2) With a timeout, you can have a postMessage child window for the parent. Then the parent window will know when the child is ready.

+8
source share

You open a window and send a message one after another. There is no way for an open document to be ready to receive a message. Try deferring the postMessage call until the window finishes loading.

A very easy way to check this is to wrap w.postMessage () in setTimeout (for 10 seconds) and see if it can publish it when the document is ready.

0
source share

All Articles