|
| 1 | +--- |
| 2 | +title: MessageChannel and MessagePort |
| 3 | +description: The MessageChannel and MessagePort APIs are now available in Workers |
| 4 | +products: |
| 5 | + - workers |
| 6 | +date: 2025-08-11T01:00:00Z |
| 7 | +--- |
| 8 | + |
| 9 | +A minimal implementation of the [MessageChannel API](https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel) is now available in Workers. This means that you can use `MessageChannel` to send messages between different parts of your Worker, but not across different Workers. |
| 10 | + |
| 11 | +The `MessageChannel` and `MessagePort` APIs will be available by default at the global scope |
| 12 | +with any worker using a compatibility date of `2025-08-15` or later. It is also available |
| 13 | +using the `expose_global_message_channel` compatibility flag, or can be explicitly disabled |
| 14 | +using the `no_expose_global_message_channel` compatibility flag. |
| 15 | + |
| 16 | +```js |
| 17 | +const { port1, port2 } = new MessageChannel(); |
| 18 | + |
| 19 | +port2.onmessage = (event) => { |
| 20 | + console.log('Received message:', event.data); |
| 21 | +}; |
| 22 | + |
| 23 | +port2.postMessage('Hello from port2!'); |
| 24 | +``` |
| 25 | + |
| 26 | +Any value that can be used with the `structuredClone(...)` API can be sent over the port. |
| 27 | + |
| 28 | +## Differences |
| 29 | + |
| 30 | +There are a number of key limitations to the `MessageChannel` API in Workers: |
| 31 | + |
| 32 | +* Transfer lists are currently not supported. This means that you will not be able to transfer |
| 33 | + ownership of objects like `ArrayBuffer` or `MessagePort` between ports. |
| 34 | +* The `MessagePort` is not yet serializable. This means that you cannot send a `MessagePort` object |
| 35 | + through the `postMessage` method or via JSRPC calls. |
| 36 | +* The `'messageerror'` event is only partially supported. If the `'onmessage'` handler throws an |
| 37 | + error, the `'messageerror'` event will be triggered, however, it will not be triggered when there |
| 38 | + are errors serializing or deserializing the message data. Instead, the error will be thrown when |
| 39 | + the `postMessage` method is called on the sending port. |
| 40 | +* The `'close'` event will be emitted on both ports when one of the ports is closed, however it |
| 41 | + will not be emitted when the Worker is terminated or when one of the ports is garbage collected. |
0 commit comments