Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. Channel Messaging API

Channel Messaging API

Note: This feature is available inWeb Workers.

TheChannel Messaging API allows two separate scripts running in different browsing contexts attached to the same document (e.g., two IFrames, or the main document and an IFrame, two documents via aSharedWorker, or two workers) to communicate directly, passing messages between one another through two-way channels (or pipes) with a port at each end.

Concepts and usage

A message channel is created using theMessageChannel() constructor. Once created, the two ports of the channel can be accessed through theMessageChannel.port1 andMessageChannel.port2 properties (which both returnMessagePort objects.) The app that created the channel usesport1, and the app at the other end of the port usesport2 — you send a message toport2, and transfer the port over to the other browsing context usingwindow.postMessage along with two arguments (the message to send, and the object to transfer ownership of, in this case the port itself.)

When these transferable objects are transferred, they are no longer usable on the context they previously belonged to. A port, after it is sent, can no longer be used by the original context.

The other browsing context can listen for the message usingonmessage, and grab the contents of the message using the event'sdata attribute. You could then respond by sending a message back to the original document usingMessagePort.postMessage.

When you want to stop sending messages down the channel, you can invokeMessagePort.close to close the ports.

Find out more about how to use this API inUsing channel messaging.

Interfaces

MessageChannel

Creates a new message channel to send messages across.

MessagePort

Controls the ports on the message channel, allowing sending of messages from one port and listening out for them arriving at the other.

Examples

Specifications

Specification
HTML
# channel-messaging

Browser compatibility

api.MessageChannel

api.MessagePort

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp