We're looking for a user researcher to understand the needs of developers and designers. Is this you or someone you know? Check out the post: https://mzl.la/2IGzdXS

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 WindowWorker, or SharedWorker). The message is received in the "message" event on navigator.serviceWorker

Syntax

Client.postMessage(message[, transfer]);

Parameters

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

Return value

Void.

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.
Working Draft Initial definition.

Browser compatibility

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support45 ?441 No32 No
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Basic support4545 No4432 No5.0

1. Service workers (and Push) have been disabled in the Firefox 45 & 52 Extended Support Releases (ESR).

Document Tags and Contributors

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