MDN wants to learn about developers like you: https://qsurvey.mozilla.com/s3/MDN-dev-survey

This is an experimental technology
Because this technology's specification has not stabilized, check the compatibility table for usage in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the specification changes.

The postMessage() method of Client 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]);

Returns

Void.

Parameters

message
The message to send to the service worker. Can be any structured-clonable type.
transfer Optional
A sequence of objects to transfer. These objects must also be present in the message.

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 Workers
The definition of 'postMessage()' in that specification.
Editor's Draft Initial definition.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 45.0[1] 44.0 (44.0)[2] No support ? No support
Feature Android Android Webview Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support 45.0[1] No support 44.0 (44.0) ? No support ? No support 45.0 [1]

Document Tags and Contributors

 Contributors to this page: jaffathecake, chrisdavidmills, jpmedley, fscholz, kscarfone
 Last updated by: jaffathecake,