如何跨域使用 window.postMessage?

看起来 Window.postMessage的重点是允许不同域名上的窗口/帧之间的安全通信,但实际上似乎并不像 Chrome 中的 允许那样。

情况是这样的:

  1. 在域 A 的页面中嵌入一个 < iframe > (域 B*上有一个 src)
  2. < iframe > 最终主要是一个 < script > 标记,最后执行..。
  3. 我调用 window.postMessage (一些数据翻译)

< iframe > 绝对是在域 B 的上下文中,我已经确认了 < iframe > 中嵌入的 javascript 正确执行并使用正确的值调用 postMessage

我在 Chrome 浏览器中得到这个错误消息:

无法将邮件发送到 A。 收件人来自 B

下面是在 A 的页面中注册消息事件侦听器的代码:

window.addEventListener(
"message",
function (event) {
// Do something
},
false);

我还尝试调用 window.postMessage(some_data, '*'),但所做的只是抑制错误。

我是不是忽略了一个重点,就是 window.postMessage (...)不是用来做这个的?还是我做错了?

* Mime-type text/html,它必须保留。

164319 次浏览

Here is an example that works on Chrome 5.0.375.125.

The page B (iframe content):

<html>
<head></head>
<body>
<script>
top.postMessage('hello', 'A');
</script>
</body>
</html>

Note the use of top.postMessage or parent.postMessage not window.postMessage here

The page A:

<html>
<head></head>
<body>
<iframe src="B"></iframe>
<script>
window.addEventListener( "message",
function (e) {
if(e.origin !== 'B'){ return; }
alert(e.data);
},
false);
</script>
</body>
</html>

A and B must be something like http://domain.example

From another question, it looks the domains(A and B here) must have a / for the postMessage to work properly.

Probably you try to send your data from mydomain.example to www.mydomain.example or reverse, NOTE you missed "www". http://mydomain.example and http://www.mydomain.example are different domains to JavaScript.

You should post a message from frame to parent, after loaded.

frame script:

$(document).ready(function() {
window.parent.postMessage("I'm loaded", "*");
});

And listen it in parent:

function listenMessage(msg) {
alert(msg);
}


if (window.addEventListener) {
window.addEventListener("message", listenMessage, false);
} else {
window.attachEvent("onmessage", listenMessage);
}

Use this link for more info: http://en.wikipedia.org/wiki/Web_Messaging