This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
The postMessage()
method of Client
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
.
Client.postMessage(message[, transfer]);
message
transfer Optional
Void.
Sending a message from a service worker to a client:
addEventListener('fetch', event => { event.waitUntil(async function() { // 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. self.clients.matchAll().then(function (clients){ clients.forEach(function(client){ client.postMessage({ msg: "Hey I just got a fetch from you!", url: event.request.url }); }); }); }()); });
Receiving that message:
navigator.serviceWorker.addEventListener('message', event => { console.log(event.data.msg, event.data.url); });
Specification | Status | Comment |
---|---|---|
Service Workers The definition of 'postMessage()' in that specification. | Working Draft | Initial definition. |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | 45 | ? | 44
|
No | 32 | No |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | 45 | 45 | No | 44 | 32 | No | 5.0 |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Client/postMessage