|
| 1 | +--- |
| 2 | +pcx_content_type: configuration |
| 3 | +title: MessageChannel |
| 4 | +head: [] |
| 5 | +description: Channel messaging with MessageChannel and MessagePort |
| 6 | + |
| 7 | +--- |
| 8 | + |
| 9 | +## Background |
| 10 | + |
| 11 | +The [MessageChannel API](https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel) provides a way to create a communication channel between different parts of your application. |
| 12 | + |
| 13 | +The Workers runtime provides a minimal implementation of the `MessageChannel` API that is |
| 14 | +currently limited to uses with a single Worker instance. This means that you can use `MessageChannel` to send messages between different parts of your Worker, but not across different Workers. |
| 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