MessageChannel
允许创建一个新的消息通道, 并通过它的两个 MessagePort 属性发送数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| const channel = new MessageChannel(); const output = document.querySelector(".output"); const iframe = document.querySelector("iframe");
channel.port1.onmessage = function(e) { output.innerHTML = e.data; };
iframe.addEventListener("load", iframeLoaded, false); function iframeLoaded() { iframe.contentWindow.postMessage('Hello from the main page!', '*', [channel.port2]); }
window.addEventListener('message', (evt) => { const messagePort = evt.ports?.[0]; messagePort.postMessage('Hello from the iframe!'); })
|