window.postMessage无法从iframe到父文档

chr*_*son 7 javascript iframe postmessage

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

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

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

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

window.parent.postMessage('message', '*');
Run Code Online (Sandbox Code Playgroud)

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

我知道将*用作targetOrigin并不总是安全的,但是在这一点上,我只想整理一下链接。

有什么想法或明显的我想念的东西吗?

Jam*_*ruk 6

确保您的回调函数在将其传递到方法之前receiveMessage()已声明。addEventListener

这是修改后的父脚本:

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


bN_*_*bN_ 5

我遇到了完全相同的问题,并通过移动 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>
Run Code Online (Sandbox Code Playgroud)

iframe 的内容很简单:

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

如果我将“脚本”部分放在文档底部,则它不再起作用...