你如何跨域使用window.postMessage? [英] How do you use window.postMessage across domains?
问题描述
好像 window.postMessage 的要点是允许安全通信在不同的域名托管的Windows /框架之间,但它实际上并没有在Chrome中允许。
以下是这种情况: p>
- 嵌入< iframe> (在域B * 上的
src
)在域A上的页面上 - < iframe> ;最终主要是< script>标记,然后执行...
- 我调用window.postMessage( some_data , page_on_A )
< iframe>绝对是在域B的上下文中,并且我已经确认嵌入式JavaScript在< iframe>正确执行并使用正确的值调用 postMessage
。
我在Chrome中收到此错误消息:
无法将讯息发布到 A 。
收件人有原始的 B 。
这里是注册消息事件监听器的代码A:
window.addEventListener(
message,
function(event){
//做某事
},
false);
我也试着调用 window.postMessage(some_data,'*' )
,但所有这一切都是压制错误。
我只是在这里忽略了一点,是window.postMessage(...)不是为了这个?或者我只是在做可怕的错误?
$ b
* Mime-type text / html,它必须保留。
下面是一个适用于Chrome 5.0.375.125的示例。
iframe内容):
< html>
< head>< / head>
< body>
< script>
top.postMessage('hello','A');
< / script>
< / body>
< / html>
请注意使用 top.postMessage
或 parent.postMessage
不是 window.postMessage
此处
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和B必须是 http://domain.com
编辑:
From 另一个问题,它看起来域(A和B在这里)必须有一个 /
postMessage
才能正常工作。
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.
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.com
EDIT:
From another question, it looks the domains(A and B here) must have a /
for the postMessage
to work properly.
这篇关于你如何跨域使用window.postMessage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!