ServiceWorkerContainer: message event
The message event is used in a page controlled by a service worker to receive messages from the service worker.
This event is not cancelable and does not bubble.
Syntax
Use the event name in methods like addEventListener(), or set an event handler property.
js
addEventListener("message", (event) => {});
onmessage = (event) => {};
Event type
A MessageEvent. Inherits from Event.
Event properties
This interface also inherits properties from its parent, Event.
MessageEvent.dataRead only-
The data sent by the message emitter.
MessageEvent.originRead only-
A string representing the origin of the message emitter.
MessageEvent.lastEventIdRead only-
A string representing a unique ID for the event.
MessageEvent.sourceRead only-
A
MessageEventSource(which can be a WindowProxy,MessagePort, orServiceWorkerobject) representing the message emitter. MessageEvent.portsRead only-
An array of
MessagePortobjects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker).
Examples
In this example the service worker get the client's ID from a fetch event and then sends it a message using Client.postMessage:
js
// service-worker.js
async function messageClient(clientId) {
const client = await clients.get(clientId);
client.postMessage("Hi client!");
}
addEventListener("fetch", (event) => {
messageClient(event.clientId);
event.respondWith(() => {
// …
});
});
The client can receive the message by listening to the message event:
js
// main.js
navigator.serviceWorker.addEventListener("message", (message) => {
console.log(message);
});
Alternatively, the client can receive the message with the onmessage event handler:
js
// main.js
navigator.serviceWorker.onmessage = (message) => {
console.log(message);
};
Specifications
| Specification |
|---|
| Service Workers # dom-serviceworkercontainer-onmessage |
Browser compatibility
BCD tables only load in the browser