aboutsummaryrefslogtreecommitdiff
path: root/files/fr/web/api/worker/postmessage/index.html
blob: d8a3e7be93dc37eec0f49fdeb8d15f72381155e8 (plain)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
---
title: Worker.postMessage()
slug: Web/API/Worker/postMessage
translation_of: Web/API/Worker/postMessage
---
<p>{{ apiref("Worker") }}</p>

<p>La méthode <code><strong>Worker.postMessage()</strong></code> envoie un message à la portée locale du worker. Cette fonction accepte un seul paramètre, qui est la donnée à envoyer au worker. Cette donnée peut-être de n'importe quelle valeur ou un objet JavaScript pris en charge par l'algorithme de clone structuré, qui inclut les références cycliques.</p>

<p>Le Worker peut renvoyer une information au thread qui l'a créé en utilisant la méthode {{domxref("DedicatedWorkerGlobalScope.postMessage")}}.</p>

<h2 id="Syntaxe">Syntaxe</h2>

<pre class="syntaxbox"><em>worker.</em>postMessage(<em>aMessage</em>, <em>[transferList</em>]);</pre>

<h3 id="Paramètres">Paramètres</h3>

<dl>
 <dt><em>aMessage</em></dt>
 <dd>L'objet à envoyer au worker; il va être dans le champ de donnée <code>data</code> dans l'évènement délivré au gestonnaire d'évènement {{domxref("Worker.onmessage")}}. Cette donnée peut être de n'importe quelle valeur ou un objet JavaScript pris en charge par l'algorithme de <a href="/fr/docs/Web/API/Web_Workers_API/algorithme_clonage_structure">clone structuré</a>, qui inclut les références cycliques.</dd>
 <dt><em>transferList</em> {{optional_inline}}</dt>
 <dd>Un tableau optionnel d'objets {{domxref("Transferable")}} desquels on doit transférer la propriété. Si la propriété d'un objet est transférée, il devient inutilisable (<em>neutralisé</em>) pour le contexte émétteur et devient disponible uniquement pour le worker auquel cela a été envoyé.</dd>
 <dd>Seulement des objets de types {{domxref("MessagePort")}}, {{domxref("ArrayBuffer")}} ou {{domxref("ImageBitmap")}} peuvent être transférés. <code>null</code> n'est pas une valeur accéptée pour <code>transfer</code>.</dd>
 <dt>
 <h3 id="Retour">Retour</h3>
 </dt>
</dl>

<p>Vide.</p>

<h2 id="Exemple">Exemple</h2>

<p>L'extrait de code suivant montre la création d'un objet {{domxref("Worker")}} en utilisant le constructeur {{domxref("Worker.Worker", "Worker()")}}. Quand les deux champs de formulaire (<code>fisrt</code> et <code>second</code>) ont été changés, les évènements {{event("change")}} invoquent <code>postMessage()</code> pour envoyer la valeur des deux entrées au <em>worker</em> courant.</p>

<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">var</span> myWorker <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Worker</span><span class="punctuation token">(</span><span class="string token">'worker.js'</span><span class="punctuation token">)</span><span class="punctuation token">;</span>

first<span class="punctuation token">.</span><span class="function function-variable token">onchange</span> <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
  myWorker<span class="punctuation token">.</span><span class="function token">postMessage</span><span class="punctuation token">(</span><span class="punctuation token">[</span>first<span class="punctuation token">.</span>value<span class="punctuation token">,</span>second<span class="punctuation token">.</span>value<span class="punctuation token">]</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
  console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">'Message posted to worker'</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span>

second<span class="punctuation token">.</span><span class="function function-variable token">onchange</span> <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
  myWorker<span class="punctuation token">.</span><span class="function token">postMessage</span><span class="punctuation token">(</span><span class="punctuation token">[</span>first<span class="punctuation token">.</span>value<span class="punctuation token">,</span>second<span class="punctuation token">.</span>value<span class="punctuation token">]</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
  console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">'Message posted to worker'</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span></code></pre>

<p>Pour l'exemple en entier, voir <a href="https://github.com/mdn/simple-web-worker">Basic dedicated worder example</a> (<a href="http://mdn.github.io/simple-web-worker/">démonstration</a>).</p>

<div class="blockIndicator note">
<p><strong>Remarque:</strong> <code>postMessage()</code> peut n'envoyer qu'un objet à la fois. Comme ci-dessus, si vous voulez envoyez plusieurs valeurs, vous pouvez utiliser un tableau.</p>
</div>

<h3 id="Exemple_de_transfert">Exemple de transfert</h3>

<p>Cette exemple montre une extension pour Firefox qui transfert un <code>ArrarBuffer</code> depuis le <em>thread</em> principal vers le <code>ChromeWorker</code>, et le <code>ChromeWorker</code> répond au le thread principal.</p>

<h4 id="Main_thread_code">Main thread code:</h4>

<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">var</span> myWorker <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">ChromeWorker</span><span class="punctuation token">(</span>self<span class="punctuation token">.</span>path <span class="operator token">+</span> <span class="string token">'myWorker.js'</span><span class="punctuation token">)</span><span class="punctuation token">;</span>

<span class="keyword token">function</span> <span class="function token">handleMessageFromWorker</span><span class="punctuation token">(</span><span class="parameter token">msg</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
    console<span class="punctuation token">.</span><span class="function token">log</span><span class="punctuation token">(</span><span class="string token">'incoming message from worker, msg:'</span><span class="punctuation token">,</span> msg<span class="punctuation token">)</span><span class="punctuation token">;</span>
    <span class="keyword token">switch</span> <span class="punctuation token">(</span>msg<span class="punctuation token">.</span>data<span class="punctuation token">.</span>aTopic<span class="punctuation token">)</span> <span class="punctuation token">{</span>
        <span class="keyword token">case</span> <span class="string token">'do_sendMainArrBuff'</span><span class="punctuation token">:</span>
            <span class="function token">sendMainArrBuff</span><span class="punctuation token">(</span>msg<span class="punctuation token">.</span>data<span class="punctuation token">.</span>aBuf<span class="punctuation token">)</span>
            <span class="keyword token">break</span><span class="punctuation token">;</span>
        <span class="keyword token">default</span><span class="punctuation token">:</span>
            <span class="keyword token">throw</span> <span class="string token">'no aTopic on incoming message to ChromeWorker'</span><span class="punctuation token">;</span>
    <span class="punctuation token">}</span>
<span class="punctuation token">}</span>

myWorker<span class="punctuation token">.</span><span class="function token">addEventListener</span><span class="punctuation token">(</span><span class="string token">'message'</span><span class="punctuation token">,</span> handleMessageFromWorker<span class="punctuation token">)</span><span class="punctuation token">;</span>

<span class="comment token">// Ok lets create the buffer and send it</span>
<span class="keyword token">var</span> arrBuf <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">ArrayBuffer</span><span class="punctuation token">(</span><span class="number token">8</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
console<span class="punctuation token">.</span><span class="function token">info</span><span class="punctuation token">(</span><span class="string token">'arrBuf.byteLength pre transfer:'</span><span class="punctuation token">,</span> arrBuf<span class="punctuation token">.</span>byteLength<span class="punctuation token">)</span><span class="punctuation token">;</span>

myWorker<span class="punctuation token">.</span><span class="function token">postMessage</span><span class="punctuation token">(</span>
    <span class="punctuation token">{</span>
        aTopic<span class="punctuation token">:</span> <span class="string token">'do_sendWorkerArrBuff'</span><span class="punctuation token">,</span>
        aBuf<span class="punctuation token">:</span> arrBuf <span class="comment token">// The array buffer that we passed to the transferrable section 3 lines below</span>
    <span class="punctuation token">}</span><span class="punctuation token">,</span>
    <span class="punctuation token">[</span>
        arrBuf <span class="comment token">// The array buffer we created 9 lines above</span>
    <span class="punctuation token">]</span>
<span class="punctuation token">)</span><span class="punctuation token">;</span>

console<span class="punctuation token">.</span><span class="function token">info</span><span class="punctuation token">(</span><span class="string token">'arrBuf.byteLength post transfer:'</span><span class="punctuation token">,</span> arrBuf<span class="punctuation token">.</span>byteLength<span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre>

<h4 id="Worker_code">Worker code</h4>

<pre class="brush: js line-numbers language-js"><code class="language-js">self<span class="punctuation token">.</span><span class="function function-variable token">onmessage</span> <span class="operator token">=</span> <span class="keyword token">function</span> <span class="punctuation token">(</span><span class="parameter token">msg</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
    <span class="keyword token">switch</span> <span class="punctuation token">(</span><span class="parameter token">msg<span class="punctuation token">.</span>data<span class="punctuation token">.</span>aTopic</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
        <span class="keyword token">case</span> <span class="string token">'do_sendWorkerArrBuff'</span><span class="punctuation token">:</span>
               <span class="function token"> sendWorkerArrBuff</span><span class="punctuation token">(</span>msg<span class="punctuation token">.</span>data<span class="punctuation token">.</span>aBuf<span class="punctuation token">)</span>
            <span class="keyword token">break</span><span class="punctuation token">;</span>
        <span class="keyword token">default</span><span class="punctuation token">:</span>
            <span class="keyword token">throw</span> <span class="string token">'no aTopic on incoming message to ChromeWorker'</span><span class="punctuation token">;</span>
    <span class="punctuation token">}</span>
<span class="punctuation token">}</span>

<span class="keyword token">function</span> <span class="function token">sendWorkerArrBuff</span><span class="punctuation token">(</span><span class="parameter token">aBuf</span><span class="punctuation token">)</span> <span class="punctuation token">{</span>
    console<span class="punctuation token">.</span><span class="function token">info</span><span class="punctuation token">(</span><span class="string token">'from worker, PRE send back aBuf.byteLength:'</span><span class="punctuation token">,</span> aBuf<span class="punctuation token">.</span>byteLength<span class="punctuation token">)</span><span class="punctuation token">;</span>

    self<span class="punctuation token">.</span><span class="function token">postMessage</span><span class="punctuation token">(</span><span class="punctuation token">{</span>aTopic<span class="punctuation token">:</span><span class="string token">'do_sendMainArrBuff'</span><span class="punctuation token">,</span> aBuf<span class="punctuation token">:</span>aBuf<span class="punctuation token">}</span><span class="punctuation token">,</span> <span class="punctuation token">[</span>aBuf<span class="punctuation token">]</span><span class="punctuation token">)</span><span class="punctuation token">;</span>

    console<span class="punctuation token">.</span><span class="function token">info</span><span class="punctuation token">(</span><span class="string token">'from worker, POST send back aBuf.byteLength:'</span><span class="punctuation token">,</span> aBuf<span class="punctuation token">.</span>byteLength<span class="punctuation token">)</span><span class="punctuation token">;</span>
<span class="punctuation token">}</span></code></pre>

<h4 id="Output_logged">Output logged</h4>

<pre class="line-numbers language-html"><code class="language-html">arrBuf.byteLength pre transfer: 8                              bootstrap.js:40
arrBuf.byteLength post transfer: 0                             bootstrap.js:42

from worker, PRE send back aBuf.byteLength: 8                  myWorker.js:5:2

incoming message from worker, msg: message { ... }             bootstrap.js:20
got back buf in main thread, aBuf.byteLength: 8                bootstrap.js:12

from worker, POST send back aBuf.byteLength: 0                 myWorker.js:7:2</code></pre>

<p><code>byteLength</code> passe à 0 quand il est transferré. Pour voir l'exemple de cette extension de démonstration de Firefox, voir <a href="https://github.com/Noitidart/ChromeWorker/tree/aca57d9cadc4e68af16201bdecbfb6f9a6f9ca6b">GitHub :: ChromeWorker - demo-transfer-arraybuffer</a></p>

<h2 id="Spécifications">Spécifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Spécification</th>
   <th scope="col">Statut</th>
   <th scope="col">Commentaire</th>
  </tr>
  <tr>
   <td>{{SpecName('HTML WHATWG', "#dom-worker-postmessage", "Worker.postMessage()")}}</td>
   <td>{{Spec2('HTML WHATWG')}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="Compatibilité_des_navigateurs">Compatibilité des navigateurs</h2>

<div>


<p>{{Compat("api.Worker.postMessage")}}</p>
[1] Internet Explorer ne supporte pas les objets {{domxref("Transferable")}}.</div>

<h2 id="Voir_aussi">Voir aussi</h2>

<ul>
 <li>L'interface {{domxref("Worker")}} auquel il appartient.</li>
</ul>