-
Notifications
You must be signed in to change notification settings - Fork 8k
/
index.md
57 lines (41 loc) · 1.65 KB
/
index.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
---
title: Client.postMessage()
slug: Web/API/Client/postMessage
---
{{SeeCompatTable}}{{APIRef("Client")}}
La méthode **`postMessage()`** de l'interface [`Client`](/fr/docs/Web/API/Client) permet à un service worker client d'envoyer un message à un [`ServiceWorker`](/fr/docs/Web/API/ServiceWorker).
## Syntaxe
```js
Client.postMessage(message[, transfer]);
```
### Valeur de retour
Void.
### Paramètres
- `message`
- : Le message à envoyer au service worker.
- `transfer {{optional_inline}}`
- : Un objet transferable, comme par exemple une référence à un port.
## Exemples
Ce fragment de code est tiré de l'[exemple d'envoi de message du service worker](https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/post-message/index.html) exemple d'envoi de message du service worker (voir [exemple en ligne](https://googlechrome.github.io/samples/service-worker/post-message/)). Le code envoi un message et transfert le port vers le service worker qui pourra répondre via {{domxref("Client.postMessage()")}}.
Ce message est contenu dans une promesse qui se résolvera si la réponse ne contient pas d'erreur et qui échouera avec l'erreur.
```js
function sendMessage(message) {
return new Promise(function (resolve, reject) {
var messageChannel = new MessageChannel();
messageChannel.port1.onmessage = function (event) {
if (event.data.error) {
reject(event.data.error);
} else {
resolve(event.data);
}
};
navigator.serviceWorker.controller.postMessage(message, [
messageChannel.port2,
]);
});
}
```
## Spécifications
{{Specifications}}
## Compatibilité des navigateurs
{{Compat}}