Listening for Messages: The Message Event
What you'll learn: How to set up listeners that receive data sent via postMessage in workers, iframes, and other messaging contexts.
The Core Idea
Once you've sent a message using postMessage, the receiving context needs a way to catch that message. That's where the message event comes in. You attach an event listener (just like you would for clicks or key presses) that fires whenever a message arrives. The event object contains the data you sent, accessible via its data property.
Think of it like subscribing to a mailbox: postMessage is someone sending you a letter, and the message event listener is you checking your mailbox and opening whatever arrives.
Setting Up a Listener
In the receiving context (whether it's a worker, the main thread, or an iframe), you listen for the 'message' event:
// In a web worker script
self.addEventListener('message', (event) => {
const receivedData = event.data;
console.log('Worker received:', receivedData);
});
Or from the main thread listening to a worker:
const worker = new Worker('worker.js');
worker.addEventListener('message', (event) => {
console.log('Main thread received:', event.data);
});
The event.data property holds whatever was passed to postMessage—strings, objects, arrays, or transferable objects.
Why This Matters
The message event is your only communication channel in isolated contexts like workers. Without it, sent data would vanish into the void. This event-driven pattern keeps contexts decoupled while enabling bidirectional communication: both sides can send and both can listen.
Key Takeaway: The message event listener is how you receive data sent via postMessage. Always access the payload through event.data in your handler function.