8

postMessage的文档暗示跨域消息传递是可能的。然而:

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

这不是一个非常清楚的说明如何实际做到这一点。

想象两个网站:

  1. [家长] 托管在qc-a.nfshost.com
  2. [儿童] 托管在qc-b.quadhome.com

在父级中:

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');
}

而且,在孩子身上:

document.addEventListener('message', function(e) {
  alert('Child got (from ' + e.origin + '): ' + e.data);
}, false);

window.opener.postMessage('Ready!', 'http://qc-a.nfshost.com');

一切都无济于事。

帮助?

4

2 回答 2

8

目前,我看到两个问题。代码中的轻微错误和超时问题。

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.

于 2010-07-26T07:32:44.003 回答
0

您正在打开窗口并在彼此之后发布消息。打开的文档不可能准备好接受发布的消息。尝试延迟 postMessage 调用,直到窗口完成加载。

一个非常简单的测试方法是将 w.postMessage() 包装在一个 setTimeout 中(10 秒),看看它是否可以在文档准备好时发布它。

于 2010-07-26T06:51:04.163 回答