ServiceWorkerGlobalScope: message event

The message event of the Service Worker API occurs when incoming messages are received. Controlled pages can use the MessagePort.postMessage() method to send messages to service workers.
The service worker can optionally send a response back via the MessagePort exposed in event.data.port, corresponding to the controlled page.

Bubbles No
Cancelable No
Interface MessageEvent
Event handler property onmessage

Examples

In thie example a page gets a handle to the ServiceWorker object via ServiceWorkerRegistration.active, and then calls its postMessage function.

// in the page being controlled
const swPath = 'static/scripts/sw.js';

function handleServiceWorkerActive(registration) {
    if (registration.active) {
        const serviceWorker = registration.active;
        const button = document.querySelector('#worker-message');
        button.addEventListener('click', ()  => {
            serviceWorker.postMessage('Hi service worker');
        });
    }
}

navigator.serviceWorker.register(swPath).then(handleServiceWorkerActive);

The service worker can receive the message by listening to the message event:

// in the service worker
addEventListener('message', (event) => {
    console.log(`The client sent me a message: ${event.data}`);
});

Specifications

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

Browser compatibility

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
message event
Experimental
Chrome Full support 40Edge ? Firefox Full support 44
Notes
Full support 44
Notes
Notes Service workers (and Push) have been disabled in the Firefox 45 and 52 Extended Support Releases (ESR).
IE No support NoOpera Full support 24Safari Full support 11.1WebView Android Full support 40Chrome Android Full support 40Firefox Android Full support 44Opera Android Full support 24Safari iOS Full support 11.1Samsung Internet Android Full support 4.0

Legend

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

See also