The postMessage()
method of the ServiceWorker
interface sends a message to the worker. This accepts a single parameter, which is the data to send to the worker. The data may be any JavaScript object which can be handled by the structured clone algorithm.
The service worker can send back information to its clients by using the postMessage()
method. The message will not be sent back to this ServiceWorker
object but to the associated ServiceWorkerContainer
available via navigator.serviceWorker
.
postMessage(message)
postMessage(message, options)
postMessage(message, transfer)
message
-
The object to deliver to the worker; this will be in the data
field in the event delivered to the message
event. This may be any JavaScript object handled by the structured clone algorithm.
The message
parameter is mandatory. If the data to be passed to the worker is unimportant, null
or undefined
must be passed explicitly.
-
options
Optional
-
An optional object containing a transfer
field with an array of transferable objects to transfer ownership of.
-
transfer
Optional
-
An optional array of transferable objects to transfer ownership of. If the ownership of an object is transferred, it becomes unusable in the context it was sent from and becomes available only to the worker it was sent to.
Transferable objects are instances of classes like ArrayBuffer
, MessagePort
or ImageBitmap
objects that can be transferred. null
is not an acceptable value for transfer
.
Note: The parameters options
and transfer
can't both be used at the same time.
In this example a ServiceWorker
is created and a message is immediately sent:
navigator.serviceWorker.register("service-worker.js");
navigator.serviceWorker.ready.then((registration) => {
registration.active.postMessage(
"Test message sent immediately after creation",
);
});
In order to receive the message, the service worker, in service-worker.js
has to listen to the message
event on its global scope.
addEventListener("message", (event) => {
console.log(`Message received: ${event.data}`);
});
Note that the service worker can send back messages to the main thread using the postMessage()
method. To receive it, the main thread needs to listen for a message
event on the ServiceWorkerContainer
object.