message (ServiceWorker)

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 message event of the Service Worker API is fired when a message is received from a service worker (ServiceWorkerMessageEvent), or a message is received in a service worker from another context (ExtendableMessageEvent.)

Bubbles No
Cancelable No
Target objects ServiceWorkerContainer, or ServiceWorkerGlobalScope, depending on context.
Interface ServiceWorkerMessageEvent or ExtendableMessageEvent, depending on context.

Examples

When the following code is used inside the main thread to set up a message channel between it and a service worker for sending messages between the two, the event object of onmessage will be a ServiceWorkerMessageEvent.

navigator.serviceWorker.ready.then(function(reg) {  
  ...
      // set up a message channel to communicate with the SW
      var channel = new MessageChannel();
      channel.port1.onmessage = function(e) {
        console.log(e);
        handleChannelMessage(e.data);
      }
      mySW = reg.active;
      mySW.postMessage('hello', [channel.port2]);
  });

Inheritance

When fired on a ServiceWorkerContainer object, the message event implements the ServiceworkerMessageEvent interface, which inherits from the Event interface — it therefore has available the properties and methods defined on both interfaces.

When fired on a ServiceWorkerGlobalScope object, the message event implements the ExtendableMessageEvent interface, which inherits from the ExtendableEvent interface — it therefore has available the properties and methods defined on both interfaces.

Specifications

Specification Status Comment
Service Workers
The definition of 'message' in that specification.
Working Draft Initial definition.

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 45.0 44.0 (44.0) No support 24 No support
Feature Android Android Webview Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support No support No support (Yes) (Yes) No support ? No support 45.0

See also

Document Tags and Contributors

 Contributors to this page: chrisdavidmills
 Last updated by: chrisdavidmills,