我正在尝试在父窗口和其中包含的 iframe 之间建立一个简单的 postmessage 通信。我在父端得到了这个代码:
var ifr = document.getElementById("ifr");
ifr.contentWindow.postMessage('hello child, this is parent', '*');
window.addEventListener('message', function (e) { console.log(e.data) });
Run Code Online (Sandbox Code Playgroud)
在孩子方面,我有:
window.parent.postMessage('hello parent, this is child', '*')
window.addEventListener('message', function (e) {console.log(e.data) } );
Run Code Online (Sandbox Code Playgroud)
我收到了 iframe 发送的消息,但没有收到父级发送的消息,我已经检查过并且 get 正确选择了 iframe 元素。这仅用于测试目的以用于其他用途。