MessagePort.onmessage
MessagePort
接口的 onmessage
事件处理程序是一个 EventListener
, 当在端口上触发一个类型为 message 的MessageEvent
时被调用 - 即,当端口接收到消息时。
备注: 此特性在 Web Worker 中可用
Syntax
channel.onmessage = function() { ... };
Example
In the following code block, you can see a new channel being created using the MessageChannel.MessageChannel
constructor. When the IFrame has loaded, we pass MessageChannel.port2
to the IFrame using MessagePort.postMessage
(en-US) along with a message. The handleMessage
handler then responds to a message being sent back from the IFrame using onmessage
, putting it into a paragraph — MessageChannel.port1
is listened to, to check when the message arrives.
js
var channel = new MessageChannel();
var para = document.querySelector("p");
var ifr = document.querySelector("iframe");
var otherWindow = ifr.contentWindow;
ifr.addEventListener("load", iframeLoaded, false);
function iframeLoaded() {
otherWindow.postMessage("Hello from the main page!", "*", [channel.port2]);
}
channel.port1.onmessage = handleMessage;
function handleMessage(e) {
para.innerHTML = e.data;
}
For a full working example, see our channel messaging basic demo on Github (run it live too).
Specifications
Specification |
---|
HTML Standard # event-message |
HTML Standard # handler-messageport-onmessage |
Browser compatibility
BCD tables only load in the browser