【问题标题】:window.postMessage not working from iframe to parent document [duplicate]window.postMessage 无法从 iframe 到父文档 [重复]
【发布时间】:2016-10-02 22:02:55
【问题描述】:

我正在尝试使用 window.postMessage API 将来自子文档(iframe)的简单消息发送回其直接父级。

在父文档中,我有以下内容:

window.addEventListener("message", receiveMessage, true);
var receiveMessage = function(event) {
    console.log("Recieved event " + JSON.stringify(event));
}

然后,在 iframe 中我有以下内容:

window.parent.postMessage('message', '*');

根据我读过的所有内容,这应该可以工作,并且我的日志消息应该写入控制台。除非它不起作用。

我知道使用 * 作为 targetOrigin 并不总是安全的,但此时我只想理清链接。

我遗漏了什么想法或任何明显的东西?

【问题讨论】:

  • 在这种情况下“不工作”是什么意思?您收到任何错误消息吗?
  • iframe 元素是否有 message 事件处理程序? postMessage() 是在 parent 窗口调用的吗?
  • 如果你真的写了你的问题,receiveMessage 在你附加它作为你的事件处理程序时仍然是未定义的。事先声明它或使用function receiveMessage(){} 表示法,以便在脚本顶部定义它。
  • @Kaiido 我编辑了我的脚本并在上游定义了 receiveMessage 函数。消息仍然没有从我的 iframe 路由。有趣的是,我还在同一 iframe 内的页面上运行了一个 FB 连接库,它正在向父级发送消息。
  • @guest271314 我认为我不需要定义在 iframe 内处理的“消息”事件。据我了解,我只需要一个父窗口的句柄,我拥有全局 window.parent 变量,然后我只需要调用 postMessage()。不过我可能错了,因为我的代码不起作用。

标签: javascript iframe postmessage


【解决方案1】:

我遇到了完全相同的问题,并通过将“脚本”部分移动到 iframe 声明上方来解决它。这是父站点的最终代码:

<script>
    window.addEventListener('message', e => {
        console.log(e.data);

        if (e.origin == "http://localhost:8080"
            && e.data == "CallFunctionA") {
            FunctionA();
        }
    }, false);

    function FunctionA() {
        window.alert('FunctionA called')
    }
</script>

<html>

<body>
    <h1>Hello static web site !!!!</h1>

    <iframe name="ifu-frame" src="http://localhost:8080/index.html" />
</body>

</html>

而 iframe 的内容很简单:

<button onclick="window.parent.postMessage('CallFunctionA', 'http://localhost:8081')">Call function A</button>

如果我将“脚本”部分放在文档的底部,那么它就不再起作用了……

【讨论】:

  • 谢谢!这就像一个魅力!
【解决方案2】:

确保您的回调函数 receiveMessage() 在传递给 addEventListener 方法之前被声明。

这是您修改后的父脚本:

var receiveMessage = function(event) {
    console.log("Recieved event " + JSON.stringify(event));
}
window.addEventListener("message", receiveMessage, true);

【讨论】:

    猜你喜欢
    • 2013-10-28
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 2019-11-22
    • 2020-02-08
    相关资源
    最近更新 更多