Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
The Channel Messaging API is a great way to send 1-to-1 messages from a window to an iframe, from a window to a Web Worker, and so on.
The BroadcastChannel API can be used to send 1-to-many messages, communicating to multiple entities at the same time.
You start by initializing a BroadcastChannel object:
const channel = new BroadcastChannel('thechannel')
To send a message on the channel you use the postMessage() method:
channel.postMessage('Hey!')
A message can be any of those supported values:
- All primitive types, excluding symbols
- Arrays
- Object literals
- String, Date, RegExp objects
- Blob,
File,FileListobjects ArrayBuffer,ArrayBufferViewobjects- FormData objects
- ImageData objects
- Map and Set objects
To receive messages from the channel, listen to the message event:
channel.onmessage = (event) => {
console.log('Received', event.data)
}
This event is fired for all listeners, except the one that is sending the message.
You can close the channel using:
channel.close() Lessons in this unit:
| 0: | Introduction |
| 1: | Web Workers |
| 2: | ▶︎ BroadcastChannel API |
| 3: | Channel Messaging API |
| 4: | requestAnimationFrame |