Web/API/Client/postMessage

From Get docs

The postMessage() method of the Client interface allows a service worker to send a message to a client (a WindowWorker, or SharedWorker). The message is received in the "message" event on navigator.serviceWorker.

Syntax

client.postMessage(message[, transfer]);
client.postMessage(message[, { transfer }]);

Parameters

message
The message to send to the client. This can be any structured-clonable type.
transfer Optional
A sequence of objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side.

Return value

undefined.

Examples

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.
    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);
});

Specifications

Specification Status Comment
Service WorkersThe definition of 'postMessage()' in that specification. Working Draft Initial definition.

Browser compatibility

Update compatibility data on GitHub

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet

postMessage

Experimental'

Chrome

Full support 45

Edge

Full support ≤79

Firefox Full support 44

Notes'

Full support 44

Notes'

Notes' Extended Support Releases (ESR) before Firefox 78 ESR do not support service workers and the Push API.

IE

No support No

Opera

Full support 32

Safari

No support No

WebView Android

Full support 45

Chrome Android

Full support 45

Firefox Android

Full support 44

Opera Android

Full support 32

Safari iOS

No support No

Samsung Internet Android

Full support 5.0

Legend

Full support  
Full support
No support  
No support
Experimental. Expect behavior to change in the future.'
Experimental. Expect behavior to change in the future.
See implementation notes.'
See implementation notes.