Skip to content

Commit

Permalink
Add ServiceWorker.postMessage (#24494)
Browse files Browse the repository at this point in the history
* Add ServiceWorker.postMessage

* Fix typos

* Fix wrong macros

* Add definition of options

* Fix old flaws

* Remove last flaw

* Update files/en-us/web/api/serviceworker/postmessage/index.md

Co-authored-by: dawei-wang <dawei-wang@users.noreply.github.com>

* Update files/en-us/web/api/serviceworker/postmessage/index.md

Co-authored-by: dawei-wang <dawei-wang@users.noreply.github.com>

* Update files/en-us/web/api/serviceworker/index.md

Co-authored-by: wbamberg <will@bootbonnet.ca>

* Update files/en-us/web/api/serviceworker/index.md

Co-authored-by: wbamberg <will@bootbonnet.ca>

* Update files/en-us/web/api/serviceworker/index.md

Co-authored-by: wbamberg <will@bootbonnet.ca>

* Update files/en-us/web/api/serviceworker/postmessage/index.md

Co-authored-by: wbamberg <will@bootbonnet.ca>

* Update files/en-us/web/api/serviceworker/postmessage/index.md

Co-authored-by: wbamberg <will@bootbonnet.ca>

* Update files/en-us/web/api/worker/postmessage/index.md

Co-authored-by: wbamberg <will@bootbonnet.ca>

* Update files/en-us/web/api/serviceworker/postmessage/index.md

Co-authored-by: wbamberg <will@bootbonnet.ca>

* Update files/en-us/web/api/serviceworker/postmessage/index.md

Co-authored-by: wbamberg <will@bootbonnet.ca>

* Update files/en-us/web/api/serviceworker/postmessage/index.md

Co-authored-by: wbamberg <will@bootbonnet.ca>

* message -> error

---------

Co-authored-by: dawei-wang <dawei-wang@users.noreply.github.com>
Co-authored-by: wbamberg <will@bootbonnet.ca>
  • Loading branch information
3 people committed Feb 17, 2023
1 parent f8161dd commit c571357
Show file tree
Hide file tree
Showing 4 changed files with 96 additions and 4 deletions.
10 changes: 8 additions & 2 deletions files/en-us/web/api/serviceworker/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,16 @@ _The `ServiceWorker` interface inherits properties from its parent, {{domxref("E

_The `ServiceWorker` interface inherits methods from its parent, {{domxref("EventTarget")}}._

- {{domxref("ServiceWorker.postMessage()")}}
- : Sends a message — consisting of any [structured-clonable](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) JavaScript object — to the service worker. The message is transmitted to the service worker using a {{domxref("ServiceWorkerGlobalScope.message_event", "message")}} event on its global scope.

## Events

- {{domxref("ServiceWorker.statechange_event", "statechange")}} {{ReadOnlyInline}}
- : Fires anytime the {{domxref("ServiceWorker.state")}} changes.
- {{domxref("ServiceWorker.statechange_event", "statechange")}}
- : Fired when {{domxref("ServiceWorker.state")}} changes.

- {{domxref("ServiceWorker.error_event", "error")}}
- : Fired when an error happens inside the `ServiceWorker` object.

## Examples

Expand Down
86 changes: 86 additions & 0 deletions files/en-us/web/api/serviceworker/postmessage/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
---
title: ServiceWorker.postMessage()
slug: Web/API/ServiceWorker/postMessage
page-type: web-api-instance-method
browser-compat: api.ServiceWorker.postMessage
---

{{APIRef("Service Workers API")}}{{securecontext_header}}

The **`postMessage()`** method of the {{domxref("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](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).

The service worker can send back information to its clients by using the {{domxref("Client.postMessage", "postMessage()")}} method. The message will not be sent back to this `ServiceWorker` object but to the associated {{domxref("ServiceWorkerContainer")}} available via {{domxref("navigator.serviceWorker")}}.

## Syntax

```js-nolint
postMessage(message)
postMessage(message, options)
postMessage(message, transfer)
```

### Parameters

- `message`

- : The object to deliver to the worker; this will be in the `data` field in the event delivered to the {{domxref("ServiceWorkerGlobalScope.message_event", "message")}} event. This may be any JavaScript object handled by the [structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/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_inline}}
- : An optional object containing a `transfer` field with an [array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of [transferable objects](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) to transfer ownership of.

- `transfer` {{optional_inline}}

- : An optional [array](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of [transferable objects](/en-US/docs/Web/API/Web_Workers_API/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 {{jsxref("ArrayBuffer")}}, {{domxref("MessagePort")}} or {{domxref("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.
### Return value

None ({{jsxref("undefined")}}).

### Exceptions

- {{jsxref("SyntaxError")}}
- : Thrown if the `message` parameter is not provided.

## Examples

In this example a {{domxref("ServiceWorker")}} is created and a message is immediately sent:

```js
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 {{domxref("ServiceWorkerGlobalScope.message_event", "message")}} event on its global scope.

```js
// This must be in `service-worker.s``
addEventListener("message", (event) =>
console.log(`Message received: ${event.data}`);
);
```

Note that the service worker can send back messages to the main thread using the {{domxref("Client.postMessage()", "postMessage()")}} method. To receive it, the main thread needs to listen for a {{domxref("ServiceWorkerContainer.message_event", "message")}} event on the {{domxref("ServiceWorkerContainer")}} object.

## Specifications

{{Specifications}}

## Browser compatibility

{{Compat}}

## See also

- The {{domxref("ServiceWorker")}} interface it belongs to.
- Its counterpart, the {{domxref("Client.postMessage()", "postMessage()")}} method that a service worker must use to send a message back to the associated {{domxref("ServiceWorkerContainer")}}.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ browser-compat: api.ServiceWorkerGlobalScope.message_event

{{APIRef("Service Workers API")}}

The **`message`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface occurs when incoming messages are received. Controlled pages can use the {{domxref("Worker.postMessage()", "ServiceWorker.postMessage()")}} method to send messages to service workers.
The **`message`** event of the {{domxref("ServiceWorkerGlobalScope")}} interface occurs when incoming messages are received. Controlled pages can use the {{domxref("ServiceWorker.postMessage()")}} method to send messages to service workers.
The service worker can optionally send a response back via the {{domxref("Client.postMessage()")}}, corresponding to the controlled page.

This event is not cancelable and does not bubble.
Expand Down
2 changes: 1 addition & 1 deletion files/en-us/web/api/worker/postmessage/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ browser-compat: api.Worker.postMessage

{{APIRef("Web Workers API")}}

The **`postMessage()`** method of the {{domxref("Worker")}} interface sends a message to the worker's inner scope. This accepts a single parameter, which is the data to send to the worker. The data may be any value or JavaScript object handled by the [structured clone](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) algorithm, which includes cyclical references.
The **`postMessage()`** method of the {{domxref("Worker")}} interface sends a message to the worker. The first parameter is the data to send to the worker. The data may be any JavaScript object that can be handled by the [structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).

The {{domxref("Worker")}} `postMessage()` method delegates to the {{domxref("MessagePort")}} {{domxref("MessagePort.postMessage", "postMessage()")}} method, which adds a task on the event loop corresponding to the receiving {{domxref("MessagePort")}}.

Expand Down

0 comments on commit c571357

Please sign in to comment.