无法执行'postMessage'到'Window': 目标源无效。

8

我有一个iframe:

<iframe id="GameFrame" 
sandbox="allow-scripts allow-pointer-lock" 
src="https://127.0.0.1:112/games/1047/play">
</iframe>

我的父页面位于:

https://127.0.0.1/arcade/not-hidden/space-blaster-1047

我正在尝试向 iFrame 发送一条消息:

var gameIframe = $("#GameFrame");
gameIframe.get(0).contentWindow.postMessage("screenshot", "");

但是这会产生错误:

未捕获的SyntaxError:在调用“postMessage”时,目标起源无效''。

其他尝试:
postMessage("screenshot", "https://127.0.0.1");

执行“postMessage”时失败,因为提供的目标源('https://127.0.0.1')与接收窗口的源('null')不匹配。

我如何将消息发送到iFrame中?


这看起来像是一个重复的问题。请参考:https://dev59.com/KmAg5IYBdhLWcg3wo8L2 - theUtherSide
2个回答

5

刚刚发现,需要使用*作为起点:

gameIframe.get(0).contentWindow.postMessage("screenshot", "*");

3
使用“*”作为目标会存在危险。这会使任何JavaScript代码通过实现addEventListener('message'...)接收到消息。MDN详细介绍了如何安全地使用postMessage。 https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage - theUtherSide
1
我在Safari上遇到了“协议、域名和端口必须匹配”的错误,即使我已经向*目标来源发送了postMessage。其他浏览器可以正常工作。Safari不支持通配符目标吗?可能的原因是什么? - fiatux

3

我在本地文件夹中运行代码时遇到了这个错误,但是当我将它放到Web服务器(Tomcat)中时,代码可以正常运行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接