父级Iframe postMessage通信

3

我想要在父窗口和包含在其中的iframe之间建立简单的postmessage通信。以下是我在父窗口的代码:

var ifr = document.getElementById("ifr");

ifr.contentWindow.postMessage('hello child, this is parent', '*');

window.addEventListener('message', function (e) { console.log(e.data) });

在孩子的一侧,我有:

window.parent.postMessage('hello parent, this is child', '*')

window.addEventListener('message', function (e) {console.log(e.data) } );

我收到了iframe发送的消息,但没有收到父级发送的消息,我已经检查过,get方法正确选择了iframe元素。这只是为了测试目的,以便在其他地方使用。


将名称设置为iframe,并使用window.frames[<index/name>]向iframe发送消息。 - Murali Mopuru
1个回答

7
当你向iframe发送消息时,它可能尚未加载。使用“onload”事件来开始与iframe的通信。
ifr.onload = function() { 
    this.contentWindow.postMessage('hello child, this is parent', '*');
};

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