如何跨域使用window.postMessage?
似乎 window.postMessage 的目的是允许 windows/ 之间的安全通信框架托管在不同的域上,但实际上 Chrome 中似乎不允许这样做。
场景如下:
- 嵌入
- (在域 B* 上有
src
)在域A 最终大部分是一个 - 我调用 window.postMessage( some_data, page_on_A
)绝对是在域 B 的上下文中,并且我已经确认
我在 Chrome 中收到此错误消息:
无法向A发布消息。 收件人来源为 B。
以下是在 A 上的页面中注册消息事件侦听器的代码:
window.addEventListener(
"message",
function (event) {
// Do something
},
false);
我也尝试过调用 window.postMessage(some_data, '*')
,但所做的只是抑制错误。
我是否只是错过了这里的要点,window.postMessage(...) 不是为此目的吗?或者我只是做错了?
*Mime-type text/html,必须保留。
It seems like the point of window.postMessage is to allow safe communication between windows/frames hosted on different domains, but it doesn't actually seem to allow that in Chrome.
Here's the scenario:
- Embed an <iframe> (with a
src
on domain B*) in a page on domain A - The <iframe> ends up being mostly a <script> tag, at the end of which's execution...
- I call window.postMessage( some_data, page_on_A )
The <iframe> is most definitely in the context of domain B, and I've confirmed that the embedded javascript in that <iframe> executes properly and calls postMessage
with the correct values.
I get this error message in Chrome:
Unable to post message to A.
Recipient has origin B.
Here's the code that registers a message event listener in the page on A:
window.addEventListener(
"message",
function (event) {
// Do something
},
false);
I've also tried calling window.postMessage(some_data, '*')
, but all that does is suppress the error.
Am I just missing the point here, is window.postMessage(...) not meant for this? Or am I just doing it horribly wrong?
*Mime-type text/html, which it must remain.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
以下是适用于 Chrome 5.0.375.125 的示例。
页面 B(iframe 内容):
注意此处使用
top.postMessage
或parent.postMessage
而不是window.postMessage
页面 A:
A B 必须类似于
http://domain.example
从另一个问题,它看起来是域(这里的 A 和 B)必须有一个
/
才能让postMessage
正常工作。Here is an example that works on Chrome 5.0.375.125.
The page B (iframe content):
Note the use of
top.postMessage
orparent.postMessage
notwindow.postMessage
hereThe page A:
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 thepostMessage
to work properly.加载后,您应该从框架向父级发布一条消息。
框架脚本:
并在父级中收听:
使用此链接获取更多信息:http://en.wikipedia.org/wiki/Web_Messaging< /a>
You should post a message from frame to parent, after loaded.
frame script:
And listen it in parent:
Use this link for more info: http://en.wikipedia.org/wiki/Web_Messaging
也许您尝试将数据从
mydomain.example
发送到www.mydomain.example
或反向发送,请注意您错过了“www”。http://mydomain.example
和http://www.mydomain.example
是 JavaScript 的不同域。Probably you try to send your data from
mydomain.example
towww.mydomain.example
or reverse, NOTE you missed "www".http://mydomain.example
andhttp://www.mydomain.example
are different domains to JavaScript.