views:

149

answers:

2

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

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

That isn't a very clear note of how to actually do it.

In the meantime, I have created two websites:

  1. Parent hosted on qc-a.nfshost.com
  2. Child hosted on qc-b.quadhome.com

In the 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.

Help?

A: 

You're opening the window & posting the message after each other. There's no way the open document will be ready to accept the post message. Try delaying the postMessage call until the window has finished loading.

A very simple way to test this is to wrap w.postMessage() in a setTimeout (for 10 seconds) and see if it can post it when the document is ready.

Ben Rowe
Right. The comment in the code mentions that there's no way (that I know) to know when the window is ready. And a 10 second timeout seems a bit... hacky.Notice in the child window, I try to do a postMessage indicating readiness back up to the opener. That fails as well. Thoughts?
Scott Robinson
+1  A: 

Currently, I am seeing two issues. Slight error in the code and the timeout issue.

1) The error I am seeing in your code is that you're using document.addEventListener. I think the right one is window.addEventListener. It is in the example on the postMessage page.

2) With the timeout, you can have the child window postMessage to the parent. The parent window will then know when the child is ready.

Anh-Kiet Ngo
In short, I'm an idiot. Replaced `document` with `window` and the ready callback worked via `window.opener.postMessage`. Thank you!
Scott Robinson
Happens to the best of us :)
Anh-Kiet Ngo