我想要在父窗口和包含在其中的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元素。这只是为了测试目的,以便在其他地方使用。