The postMessage()
method of the Client
interface allows a service worker to send a message to a client (a Window
, Worker
, or SharedWorker
). The message is received in the "message
" event on navigator.serviceWorker
.
The postMessage()
method of the Client
interface allows a service worker to send a message to a client (a Window
, Worker
, or SharedWorker
). The message is received in the "message
" event on navigator.serviceWorker
.
js
postMessage(message) postMessage(message, options) postMessage(message, transferables)
message
The message to send to the client. This can be any structured-cloneable type.
options
Optional
An optional object containing a transfer
field with an array of transferable objects to transfer ownership of. The ownership of these objects is given to the destination side and they are no longer usable on the sending side.
transferables
Optional
An optional array of transferable objects to transfer ownership of. The ownership of these objects is given to the destination side and they are no longer usable on the sending side.
None (undefined
).
Sending a message from a service worker to a client:
js
addEventListener("fetch", (event) => { event.waitUntil( (async () => { // Exit early if we don't have access to the client. // Eg, if it's cross-origin. if (!event.clientId) return; // Get the client. const client = await clients.get(event.clientId); // Exit early if we don't get the client. // Eg, if it closed. if (!client) return; // Send a message to the client. client.postMessage({ msg: "Hey I just got a fetch from you!", url: event.request.url, }); })(), ); });
Receiving that message:
js
navigator.serviceWorker.addEventListener("message", (event) => { console.log(event.data.msg, event.data.url); });
Specification |
---|
Service Workers # dom-client-postmessage-message-options |
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
postMessage |
40 | 17 | 44 | No | 27 | 11.1 | 40 | 40 | 44 | 27 | 11.3 | 4.0 |
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Client/postMessage