/[suikacvs]/markup/html/html5/spec-ja/.workers-spec.en.html
Suika

Contents of /markup/html/html5/spec-ja/.workers-spec.en.html

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.24 - (hide annotations) (download) (as text)
Sat Mar 21 06:16:48 2009 UTC (17 years ago) by wakaba
Branch: MAIN
Changes since 1.23: +1362 -1588 lines
File MIME type: text/html
make

1 wakaba 1.24 <!DOCTYPE html><html lang=en-US-x-hixie><meta charset=ascii><title>Web Workers</title><link href=/style/specification rel=stylesheet><link href=/images/icon rel=icon><body class=draft>
2 wakaba 1.1 <div class=head>
3 wakaba 1.24 <p><a class=logo href=http://www.whatwg.org/ rel=home><img alt=WHATWG src=/images/logo></a></p>
4 wakaba 1.14 <h1>Web Workers</h1>
5 wakaba 1.24 <h2 class="no-num no-toc" id=draft-recommendation-&mdash;-date:-01-jan-1901>Draft Recommendation &mdash; 20 March 2009</h2>
6     <p>You can take part in this work. <a href=http://www.whatwg.org/mailing-list>Join the working group's discussion list.</a></p>
7     <p><strong>Web designers!</strong> We have a <a href=http://blog.whatwg.org/faq/>FAQ</a>, a <a href=http://forums.whatwg.org/>forum</a>, and a <a href=http://www.whatwg.org/mailing-list#help>help mailing list</a> for you!</p>
8     <dl><dt>This version:</dt>
9     <dd><a href=http://www.whatwg.org/specs/web-workers/current-work/>http://whatwg.org/ww</a></dd>
10     <dt>Version history:</dt>
11     <dd>Twitter messages (non-editorial changes only): <a href=http://twitter.com/WHATWG>http://twitter.com/WHATWG</a></dd>
12     <dd>Commit-Watchers mailing list: <a href=http://lists.whatwg.org/listinfo.cgi/commit-watchers-whatwg.org>http://lists.whatwg.org/listinfo.cgi/commit-watchers-whatwg.org</a></dd>
13     <dd>Interactive Web interface: <a href=http://html5.org/tools/web-workers-tracker>http://html5.org/tools/web-workers-tracker</a></dd>
14     <dd>Subversion interface: <a href=http://svn.whatwg.org/webworkers/>http://svn.whatwg.org/webworkers/</a></dd>
15     <dt>Issues:</dt>
16     <dd>To send feedback: <a href=http://www.whatwg.org/mailing-list>whatwg@whatwg.org</a></dd>
17     <dd>To view and vote on feedback: <a href=http://www.whatwg.org/issues/>http://www.whatwg.org/issues/</a></dd>
18     <dt>Editor:</dt>
19     <dd>Ian Hickson, Google, ian@hixie.ch</dd>
20     </dl><p class=copyright>&copy; Copyright 2004-2008 Apple Computer, Inc.,
21     Mozilla Foundation, and Opera Software ASA.</p>
22     <p class=copyright>You are granted a license to use, reproduce
23     and create derivative works of this document.</p>
24 wakaba 1.1 </div>
25    
26 wakaba 1.24 <hr><h2 class="no-num no-toc" id=abstract>Abstract</h2>
27 wakaba 1.1
28 wakaba 1.24 <p>This specification defines an API that allows Web application
29     authors to spawn background workers running scripts in parallel to
30     their main page. This allows for thread-like operation with
31     message-passing as the coordination mechanism.</p>
32 wakaba 1.1
33    
34     <h2 class="no-num no-toc" id=status>Status of this document</h2>
35    
36 wakaba 1.24 <p><strong>This is a work in progress!</strong> This document is
37     changing on a daily if not hourly basis in response to comments and
38     as a general part of its development process. Comments are very
39     welcome, please send them to <a href=mailto:whatwg@whatwg.org>whatwg@whatwg.org</a>. Thank
40     you.</p>
41    
42     <p>The current focus is in developing a first draft proposal.</p>
43    
44     <p>Implementors should be aware that this specification is not
45     stable. <strong>Implementors who are not taking part in the
46     discussions are likely to find the specification changing out from
47     under them in incompatible ways.</strong> Vendors interested in
48     implementing this specification before it eventually reaches the
49     call for implementations should join the <a href=/mailing-list>WHATWG mailing list</a> and take part in the
50     discussions.</p>
51    
52     <p>This specification is also being produced by the <a href=http://www.w3.org/2008/webapps/>W3C Web Apps WG</a>. The two
53     specifications are identical from the table of contents onwards.</p>
54 wakaba 1.1
55     <h2 class="no-num no-toc" id=contents>Table of contents</h2>
56 wakaba 1.24
57     <!--begin-toc-->
58     <ol class=toc>
59     <li><a href=#introduction><span class=secno>1 </span>Introduction</a>
60     <ol>
61     <li><a href=#scope><span class=secno>1.1 </span>Scope</a></li>
62     <li><a href=#tutorial><span class=secno>1.2 </span>Tutorial</a>
63     <ol>
64     <li><a href=#a-background-number-crunching-worker><span class=secno>1.2.1 </span>A background number-crunching worker</a></li>
65     <li><a href=#a-worker-for-updating-a-client-side-database><span class=secno>1.2.2 </span>A worker for updating a client-side database</a></li>
66     <li><a href=#worker-used-for-background-i/o><span class=secno>1.2.3 </span>Worker used for background I/O</a></li>
67     <li><a href=#shared-workers><span class=secno>1.2.4 </span>Shared workers</a></li>
68     <li><a href=#delegation><span class=secno>1.2.5 </span>Delegation</a></li>
69     <li><a href=#providing-libraries><span class=secno>1.2.6 </span>Providing libraries</a></ol></ol></li>
70     <li><a href=#conformance-requirements><span class=secno>2 </span>Conformance requirements</a>
71     <ol>
72     <li><a href=#dependencies><span class=secno>2.1 </span>Dependencies</a></ol></li>
73     <li><a href=#terminology><span class=secno>3 </span>Terminology</a></li>
74     <li><a href=#infrastructure><span class=secno>4 </span>Infrastructure</a>
75     <ol>
76     <li><a href=#the-global-scope><span class=secno>4.1 </span>The global scope</a>
77     <ol>
78     <li><a href=#the-workerglobalscope-abstract-interface><span class=secno>4.1.1 </span>The <code>WorkerGlobalScope</code> abstract interface</a></li>
79     <li><a href=#dedicated-workers-and-the-dedicatedworkerglobalscope-interface><span class=secno>4.1.2 </span>Dedicated workers and the <code>DedicatedWorkerGlobalScope</code> interface</a></li>
80     <li><a href=#shared-workers-and-the-sharedworkerglobalscope-inteface><span class=secno>4.1.3 </span>Shared workers and the <code>SharedWorkerGlobalScope</code> inteface</a></ol></li>
81     <li><a href=#base-urls-and-origins-of-workers><span class=secno>4.2 </span>Base URLs and origins of workers</a></li>
82     <li><a href=#decoding-scripts><span class=secno>4.3 </span>Decoding scripts</a></li>
83     <li><a href=#the-event-loop><span class=secno>4.4 </span>The event loop</a></li>
84     <li><a href="#the-worker's-ports"><span class=secno>4.5 </span>The worker's ports</a></li>
85     <li><a href=#processing-model><span class=secno>4.6 </span>Processing model</a>
86     <ol>
87     <li><a href=#runtime-script-errors><span class=secno>4.6.1 </span>Runtime script errors</a></ol></li>
88     <li><a href=#creating-workers><span class=secno>4.7 </span>Creating workers</a>
89     <ol>
90     <li><a href=#the-abstractworker-abstract-interface><span class=secno>4.7.1 </span>The <code>AbstractWorker</code> abstract interface</a></li>
91     <li><a href=#dedicated-workers-and-the-worker-interface><span class=secno>4.7.2 </span>Dedicated workers and the <code>Worker</code> interface</a></li>
92     <li><a href=#shared-workers-and-the-sharedworker-interface><span class=secno>4.7.3 </span>Shared workers and the <code>SharedWorker</code> interface</a></ol></ol></li>
93     <li><a href=#apis-available-to-workers><span class=secno>5 </span>APIs available to workers</a>
94     <ol>
95     <li><a href=#importing-scripts-and-libraries><span class=secno>5.1 </span>Importing scripts and libraries</a></li>
96     <li><a href=#the-navigator-object><span class=secno>5.2 </span>The <code>Navigator</code> object</a></li>
97     <li><a href=#apis-defined-in-other-specifications><span class=secno>5.3 </span>APIs defined in other specifications</a></li>
98     <li><a href=#interface-objects-and-constructors><span class=secno>5.4 </span>Interface objects and constructors</a></li>
99     <li><a href=#worker-locations><span class=secno>5.5 </span>Worker locations</a></ol></li>
100     <li><a class=no-num href=#references>References</a></li>
101     <li><a class=no-num href=#acknowledgements>Acknowledgements</a></ol>
102     <!--end-toc-->
103     <hr><h2 id=introduction><span class=secno>1 </span>Introduction</h2>
104 wakaba 1.1
105 wakaba 1.24 <h3 id=scope><span class=secno>1.1 </span>Scope</h3>
106 wakaba 1.1
107 wakaba 1.24 <p><em>This section is non-normative.</em></p>
108 wakaba 1.1
109 wakaba 1.24 <p>This specification defines an API for running scripts in the
110     background independently of any user interface scripts.</p>
111 wakaba 1.14
112 wakaba 1.24 <p>This allows for long-running scripts that are not interrupted by
113     scripts that respond to clicks or other user interactions, and
114     allows long tasks to be executed without yielding to keep the page
115     responsive.</p>
116    
117     <p>Workers (as these background scripts are called herein) are
118     relatively heavy-weight, and are not intended to be used in large
119     numbers. For example, it would be inappropriate to launch one worker
120     for each pixel of a four megapixel image. The examples below show
121     some appropriate uses of workers.</p>
122 wakaba 1.14
123 wakaba 1.24 <p>Generally, workers are expected to be long-lived, have a high
124     start-up performance cost, and a high per-instance memory cost.</p>
125 wakaba 1.14
126    
127     <h3 id=tutorial><span class=secno>1.2 </span>Tutorial</h3>
128 wakaba 1.1
129 wakaba 1.24 <p><em>This section is non-normative.</em></p>
130 wakaba 1.1
131 wakaba 1.24 <p>There are a variety of uses that workers can be put to. The
132     following subsections show various examples of this use.</p>
133 wakaba 1.8
134 wakaba 1.24 <h4 id=a-background-number-crunching-worker><span class=secno>1.2.1 </span>A background number-crunching worker</h4>
135 wakaba 1.8
136 wakaba 1.24 <p><em>This section is non-normative.</em></p>
137 wakaba 1.8
138     <p>The simplest use of workers is for performing a computationally
139 wakaba 1.24 expensive task without interrupting the user interface.</p>
140 wakaba 1.8
141 wakaba 1.24 <p>In this example, the main document spawns a worker to
142     (na&iuml;vely) compute prime numbers, and progressively displays the
143     most recently found prime number.</p>
144    
145     <p>The main page is as follows:</p>
146    
147     <pre>&lt;!DOCTYPE HTML&gt;
148     &lt;html&gt;
149     &lt;head&gt;
150     &lt;title&gt;Worker example: One-core computation&lt;/title&gt;
151     &lt;/head&gt;
152     &lt;body&gt;
153     &lt;p&gt;The highest prime number discovered so far is: &lt;output id="result"&gt;&lt;/output&gt;&lt;/p&gt;
154     &lt;script&gt;
155 wakaba 1.12 var worker = new Worker('worker.js');
156     worker.onmessage = function (event) {
157 wakaba 1.14 document.getElementById('result').textContent = event.data;
158 wakaba 1.8 };
159 wakaba 1.24 &lt;/script&gt;
160     &lt;/body&gt;
161     &lt;/html&gt;</pre>
162    
163     <p>The <code title=dom-Worker><a href=#dom-worker>Worker()</a></code> constructor call
164     creates a worker and returns a <code><a href=#worker>Worker</a></code> object
165     representing that worker, which is used to communicate with the
166     worker. That object's <code title=handler-Worker-onmessage><a href=#handler-worker-onmessage>onmessage</a></code> event handler
167     attribute allows the code to receive messages from the worker.</p>
168 wakaba 1.8
169 wakaba 1.24 <p>The worker itself is as follows:</p>
170 wakaba 1.8
171     <pre>var n = 1;
172     search: while (true) {
173     n += 1;
174     for (var i = 2; i &lt;= Math.sqrt(n); i += 1)
175     if (n % i == 0)
176     continue search;
177     // found a prime!
178 wakaba 1.12 postMessage(n);
179 wakaba 1.8 }</pre>
180    
181     <p>The bulk of this code is simply an unoptimised search for a prime
182 wakaba 1.24 number. To send a message back to the page, the <code title=dom-DedicatedWorkerGlobalScope-postMessage><a href=#dom-dedicatedworkerglobalscope-postmessage>postMessage()</a></code>
183     method is used to post a message when a prime is found.</p>
184    
185     <p><a href=http://www.whatwg.org/demos/workers/primes/page.html>View this example online</a>.</p>
186 wakaba 1.8
187    
188    
189 wakaba 1.24 <h4 id=a-worker-for-updating-a-client-side-database><span class=secno>1.2.2 </span>A worker for updating a client-side database</h4>
190 wakaba 1.8
191 wakaba 1.24 <p><em>This section is non-normative.</em></p>
192 wakaba 1.8
193 wakaba 1.24 <p>In this example, the main document spawns a worker whose only
194     task is to listen for notifications from the server, and, when
195     appropriate, either add or remove data from the client-side
196     database.</p>
197 wakaba 1.8
198 wakaba 1.24 <p>Since no communication occurs between the worker and the main
199     page, the main page can start the worker by just doing:</p>
200    
201     <pre>&lt;script&gt;
202 wakaba 1.13 new Worker('worker.js');
203 wakaba 1.24 &lt;/script&gt;</pre>
204 wakaba 1.8
205 wakaba 1.24 <p>The worker itself is as follows:</p>
206 wakaba 1.8
207     <pre>var server = new WebSocket('ws://whatwg.org/database');
208 wakaba 1.9 var database = openDatabase('demobase', '1.0', 'Demo Database', 10240);
209 wakaba 1.8 server.onmessage = function (event) {
210     // data is in the format "command key value"
211 wakaba 1.14 var data = event.data.split(' ');
212 wakaba 1.8 switch (data[0]) {
213     case '+':
214     database.transaction(function(tx) {
215     tx.executeSql('INSERT INTO pairs (key, value) VALUES (?, ?)', data[1], data[2]);
216     });
217     case '-':
218     database.transaction(function(tx) {
219     tx.executeSql('DELETE FROM pairs WHERE key=? AND value=?', data[1], data[2]);
220     });
221     }
222     };</pre>
223    
224 wakaba 1.24 <p>This connects to the server using the <code>WebSocket</code>
225     mechanism and opens the local database (which, we presume, has been
226     created earlier). The worker then just listens for messages from the
227     server and acts on them as appropriate, forever (or until the main
228     page is closed).</p>
229    
230     <p><a href=http://www.whatwg.org/demos/workers/database-updater/page.html>View
231     this example online</a>. (This example will not actually function,
232     since the server does not actually exist and the database is not
233     created by this sample code.)</p>
234    
235    
236    
237     <h4 id=worker-used-for-background-i/o><span class=secno>1.2.3 </span>Worker used for background I/O</h4>
238    
239     <p><em>This section is non-normative.</em></p>
240    
241     <p>In this example, the main document uses two workers, one for
242     fetching stock updates for at regular intervals, and one for
243     fetching performing search queries that the user requests.</p>
244    
245     <p>The main page is as follows:</p>
246    
247     <pre>&lt;!DOCTYPE HTML&gt;
248     &lt;html&gt;
249     &lt;head&gt;
250     &lt;title&gt;Worker example: Stock ticker&lt;/title&gt;
251     &lt;script&gt;
252 wakaba 1.8 // TICKER
253     var symbol = 'GOOG'; // default symbol to watch
254 wakaba 1.12 var ticker = new Worker('ticker.js');
255 wakaba 1.8
256     // SEARCHER
257 wakaba 1.12 var searcher = new Worker('searcher.js');
258 wakaba 1.8 function search(query) {
259 wakaba 1.12 searcher.postMessage(query);
260 wakaba 1.8 }
261    
262     // SYMBOL SELECTION UI
263     function select(newSymbol) {
264     symbol = newSymbol;
265 wakaba 1.12 ticker.postMessage(symbol);
266 wakaba 1.8 }
267 wakaba 1.24 &lt;/script&gt;
268     &lt;/head&gt;
269     &lt;body&gt;
270     &lt;p&gt;&lt;output id="symbol"&gt;&lt;/output&gt; &lt;output id="value"&gt;&lt;/output&gt;&lt;/p&gt;
271     &lt;script&gt;
272 wakaba 1.12 ticker.onmessage = function (event) {
273 wakaba 1.14 var data = event.data.split(' ');
274 wakaba 1.8 document.getElementById('symbol').textContent = data[0];
275     document.getElementById('value').textContent = data[1];
276     };
277 wakaba 1.12 ticker.postMessage(symbol);
278 wakaba 1.24 &lt;/script&gt;
279     &lt;p&gt;&lt;label&gt;Search: &lt;input type="text" oninput="search(this.value)"&gt;&lt;/label&gt;&lt;/p&gt;
280     &lt;ul id="results"&gt;&lt;/ul&gt;
281     &lt;script&gt;
282 wakaba 1.12 searcher.onmessage = function (event) {
283 wakaba 1.14 var data = event.data.split(' ');
284 wakaba 1.8 var results = document.getElementById('results');
285     while (results.hasChildNodes()) // clear previous results
286     results.removeChild(results.firstChild);
287     for (var i = 0; i &lt; data.length; i += 1) {
288     // add a list item with a button for each result
289     var li = document.createElement('li');
290     var button = document.createElement('button');
291     button.value = data[i];
292     button.type = 'button';
293     button.onclick = function () { select(this.value); };
294     button.textContent = data[i];
295     li.appendChild(button);
296     results.appendChild(li);
297     }
298     };
299 wakaba 1.24 &lt;/script&gt;
300     &lt;p&gt;(The data in this example is not real. Try searching for "Google" or "Apple".)&lt;/p&gt;
301     &lt;/body&gt;
302     &lt;/html&gt;</pre>
303 wakaba 1.8
304 wakaba 1.24 <p>The two workers use a common library for performing the actual
305     network calls. This library is as follows:</p>
306 wakaba 1.8
307     <pre>function get(url) {
308 wakaba 1.12 try {
309     var xhr = new XMLHttpRequest();
310     xhr.open('GET', url, false);
311     xhr.send();
312     return xhr.responseText;
313     } catch (e) {
314     return ''; // turn all errors into empty results
315     }
316 wakaba 1.8 }</pre>
317    
318 wakaba 1.24 <p>The stock updater worker is as follows:</p>
319 wakaba 1.8
320 wakaba 1.9 <pre>importScripts('io.js');
321 wakaba 1.8 var timer;
322     var symbol;
323     function update() {
324 wakaba 1.12 postMessage(symbol + ' ' + get('stock.cgi?' + symbol));
325 wakaba 1.8 timer = setTimeout(update, 10000);
326     }
327 wakaba 1.12 onmessage = function (event) {
328 wakaba 1.8 if (timer)
329     clearTimeout(timer);
330 wakaba 1.14 symbol = event.data;
331 wakaba 1.8 update();
332     };</pre>
333    
334 wakaba 1.24 <p>The search query worker is as follows:</p>
335 wakaba 1.8
336 wakaba 1.9 <pre>importScripts('io.js');
337 wakaba 1.12 onmessage = function (event) {
338 wakaba 1.14 postMessage(get('search.cgi?' + event.data));
339 wakaba 1.8 };</pre>
340    
341 wakaba 1.24 <p><a href=http://www.whatwg.org/demos/workers/stocks/page.html>View this example online</a>.</p>
342    
343 wakaba 1.8
344 wakaba 1.23 <h4 id=shared-workers><span class=secno>1.2.4 </span>Shared workers</h4>
345 wakaba 1.8
346 wakaba 1.24 <p><em>This section is non-normative.</em></p>
347 wakaba 1.8
348 wakaba 1.24 <p>In this example, multiple windows (viewers) can be opened that
349     are all viewing the same map. All the windows share the same map
350     information, with a single worker coordinating all the viewers. Each
351     viewer can move around independently, but if they set any data on
352     the map, all the viewers are updated.</p>
353    
354     <p>The main page isn't interesting, it merely provides a way to open
355     the viewers:</p>
356    
357     <pre>&lt;!DOCTYPE HTML&gt;
358     &lt;html&gt;
359     &lt;head&gt;
360     &lt;title&gt;Workers example: Multiviewer&lt;/title&gt;
361     &lt;script&gt;
362 wakaba 1.8 function openViewer() {
363     window.open('viewer.html');
364     }
365 wakaba 1.24 &lt;/script&gt;
366     &lt;/head&gt;
367     &lt;body&gt;
368     &lt;p&gt;&lt;button type=button onclick="openViewer()"&gt;Open a new
369     viewer&lt;/button&gt;&lt;/p&gt;
370     &lt;p&gt;Each viewer opens in a new window. You can have as many viewers
371     as you like, they all view the same data.&lt;/p&gt;
372     &lt;/body&gt;
373     &lt;/html&gt;</pre>
374    
375     <p>The viewer is more involved:</p>
376    
377     <pre>&lt;!DOCTYPE HTML&gt;
378     &lt;html&gt;
379     &lt;head&gt;
380     &lt;title&gt;Workers example: Multiviewer viewer&lt;/title&gt;
381     &lt;script&gt;
382 wakaba 1.12 var worker = new SharedWorker('worker.js', 'core');
383 wakaba 1.8
384     // CONFIGURATION
385     function configure(event) {
386 wakaba 1.14 if (event.data.substr(0, 4) != 'cfg ') return;
387     var name = event.data.substr(4).split(' ', 1);
388 wakaba 1.8 // update display to mention our name is name
389     document.getElementsByTagName('h1')[0].textContent += ' ' + name;
390     // no longer need this listener
391 wakaba 1.9 worker.port.removeEventListener('message', configure, false);
392 wakaba 1.8 }
393 wakaba 1.13 worker.port.addEventListener('message', configure, false);
394 wakaba 1.8
395     // MAP
396     function paintMap(event) {
397 wakaba 1.14 if (event.data.substr(0, 4) != 'map ') return;
398     var data = event.data.substr(4).split(',');
399 wakaba 1.8 // display tiles data[0] .. data[8]
400     var canvas = document.getElementById('map');
401     var context = canvas.getContext('2d');
402     for (var y = 0; y &lt; 3; y += 1) {
403     for (var x = 0; x &lt; 3; x += 1) {
404     var tile = data[y * 3 + x];
405     if (tile == '0')
406     context.fillStyle = 'green';
407     else
408     context.fillStyle = 'maroon';
409     fillRect(x * 50, y * 50, 50, 50);
410     }
411     }
412     }
413 wakaba 1.13 worker.port.addEventListener('message', paintMap, false);
414 wakaba 1.8
415     // PUBLIC CHAT
416     function updatePublicChat(event) {
417 wakaba 1.14 if (event.data.substr(0, 4) != 'txt ') return;
418     var name = event.data.substr(4).split(' ', 1);
419     var message = event.data.substr(4 + length(name) + 1);
420 wakaba 1.24 // display "&lt;name&gt; message" in public chat
421 wakaba 1.8 var dialog = document.getElementById('public');
422     var dt = document.createElement('dt');
423     dt.textContent = name;
424     dialog.appendChild(dt);
425     var dd = document.createElement('dd');
426     dd.textContent = message;
427     dialog.appendChild(dd);
428     }
429 wakaba 1.13 worker.port.addEventListener('message', updatePublicChat, false);
430 wakaba 1.8
431     // PRIVATE CHAT
432     function startPrivateChat(event) {
433 wakaba 1.14 if (event.data.substr(0, 4) != 'msg ') return;
434     var name = event.data.substr(4).split(' ', 1);
435 wakaba 1.24 var port = event.ports[0];
436 wakaba 1.8 // display a private chat UI
437     var ul = document.getElementById('private');
438     var li = document.createElement('li');
439     var h3 = document.createElement('h3');
440     h3.textContent = 'Private chat with ' + name;
441     li.appendChild(h3);
442     var dialog = document.createElement('dialog');
443     var addMessage = function(name, message) {
444     var dt = document.createElement('dt');
445     dt.textContent = name;
446     dialog.appendChild(dt);
447     var dd = document.createElement('dd');
448     dd.textContent = message;
449     dialog.appendChild(dd);
450     };
451     port.onmessage = function (event) {
452 wakaba 1.14 addMessage(name, event.data);
453 wakaba 1.8 };
454     li.appendChild(dialog);
455     var form = document.createElement('form');
456     var p = document.createElement('p');
457     var input = document.createElement('input');
458     input.size = 50;
459     p.appendChild(input);
460     p.appendChild(document.createTextNode(' '));
461     var button = document.createElement('button');
462     button.textContent = 'Post';
463     p.appendChild(button);
464     form.onsubmit = function () {
465     port.postMessage(input.value);
466     addMessage('me', input.value);
467     input.value = '';
468     return false;
469     };
470     form.appendChild(p);
471     li.appendChild(form);
472     }
473 wakaba 1.13 worker.port.addEventListener('message', startPrivateChat, false);
474 wakaba 1.24 &lt;/script&gt;
475     &lt;/head&gt;
476     &lt;body&gt;
477     &lt;h1&gt;Viewer&lt;/h1&gt;
478     &lt;h2&gt;Map&lt;/h2&gt;
479     &lt;p&gt;&lt;canvas id="map" height=150 width=150&gt;&lt;/canvas&gt;&lt;/p&gt;
480     &lt;p&gt;
481     &lt;button type=button onclick="worker.port.postMessage('mov left')"&gt;Left&lt;/button&gt;
482     &lt;button type=button onclick="worker.port.postMessage('mov up')"&gt;Up&lt;/button&gt;
483     &lt;button type=button onclick="worker.port.postMessage('mov down')"&gt;Down&lt;/button&gt;
484     &lt;button type=button onclick="worker.port.postMessage('mov right')"&gt;Right&lt;/button&gt;
485     &lt;button type=button onclick="worker.port.postMessage('set 0')"&gt;Set 0&lt;/button&gt;
486     &lt;button type=button onclick="worker.port.postMessage('set 1')"&gt;Set 1&lt;/button&gt;
487     &lt;/p&gt;
488     &lt;h2&gt;Public Chat&lt;/h2&gt;
489     &lt;dialog id="public"&gt;&lt;/dialog&gt;
490     &lt;form onsubmit="worker.port.postMessage('txt ' + message.value); message.value = ''; return false;"&gt;
491     &lt;p&gt;
492     &lt;input type="text" name="message" size="50"&gt;
493     &lt;button&gt;Post&lt;/button&gt;
494     &lt;/p&gt;
495     &lt;/form&gt;
496     &lt;h2&gt;Private Chat&lt;/h2&gt;
497     &lt;ul id="private"&gt;&lt;/ul&gt;
498     &lt;/body&gt;
499     &lt;/html&gt;
500 wakaba 1.9 </pre>
501 wakaba 1.8
502 wakaba 1.24 <p>There are several key things worth noting about the way the
503     viewer is written.</p>
504 wakaba 1.8
505     <p><strong>Multiple listeners</strong>. Instead of a single message
506 wakaba 1.24 processing function, the code here attaches multiple event
507     listeners, each one performing a quick check to see if it is
508     relevant for the message. In this example it doesn't make much
509     difference, but if multiple authors wanted to collaborate using a
510     single port to communicate with a worker, it would allow for
511     independent code instead of changes having to all be made to a
512     single event handling function.</p>
513    
514     <p>Registering event listeners in this way also allows you to
515     unregister specific listeners when you are done with them, as is
516     done with the <code title="">configure()</code> method in this
517     example.</p>
518 wakaba 1.8
519 wakaba 1.24 <p>Finally, the worker:</p>
520 wakaba 1.8
521     <pre>
522     var nextName = 0;
523     function getNextName() {
524     // this could use more friendly names
525     // but for now just return a number
526     return nextName++;
527     }
528    
529     var map = [
530     [0, 0, 0, 0, 0, 0, 0],
531     [1, 1, 0, 1, 0, 1, 1],
532     [0, 1, 0, 1, 0, 0, 0],
533     [0, 1, 0, 1, 0, 1, 1],
534     [0, 0, 0, 1, 0, 0, 0],
535     [1, 0, 0, 1, 1, 1, 1],
536     [1, 1, 0, 1, 1, 0, 1],
537     ];
538    
539     function wrapX(x) {
540     if (x &lt; 0) return wrapX(x + map[0].length);
541 wakaba 1.24 if (x &gt;= map[0].length) return wrapX(x - map[0].length);
542 wakaba 1.8 return x;
543     }
544    
545     function wrapY(y) {
546     if (y &lt; 0) return wrapY(y + map.length);
547 wakaba 1.24 if (y &gt;= map[0].length) return wrapY(y - map.length);
548 wakaba 1.8 return y;
549     }
550    
551 wakaba 1.12 function sendMapData(callback) {
552 wakaba 1.8 var data = '';
553     for (var y = viewer.y-1; y &lt;= viewer.y+1; y += 1) {
554     for (var x = viewer.x-1; x &lt;= viewer.x+1; x += 1) {
555     if (data != '')
556     data += ',';
557     data += map[y][x];
558     }
559     }
560 wakaba 1.12 callback('map ' + data);
561 wakaba 1.8 }
562    
563     var viewers = {};
564     onconnect = function (event) {
565 wakaba 1.24 event.ports[0]._name = getNextName();
566     event.ports[0]._data = { port: event.port, x: 0, y: 0, };
567     viewers[event.ports[0]._name] = event.port._data;
568     event.ports[0].postMessage('cfg ' + name);
569     event.ports[0].onmessage = getMessage;
570     sendMapData(event.ports[0].postMessage);
571 wakaba 1.8 };
572    
573     function getMessage(event) {
574 wakaba 1.14 switch (event.data.substr(0, 4)) {
575 wakaba 1.8 case 'mov ':
576 wakaba 1.14 var direction = event.data.substr(4);
577 wakaba 1.8 var dx = 0;
578     var dy = 0;
579     switch (direction) {
580     case 'up': dy = -1; break;
581     case 'down': dy = 1; break;
582     case 'left': dx = -1; break;
583     case 'right': dx = 1; break;
584     }
585     event.target._data.x = wrapX(event.target._data.x + dx);
586     event.target._data.y = wrapY(event.target._data.y + dy);
587 wakaba 1.12 sendMapData(event.target.postMessage);
588 wakaba 1.8 break;
589     case 'set ':
590 wakaba 1.14 var value = event.data.substr(4);
591 wakaba 1.8 map[event.target._data.y][event.target._data.x] = value;
592     for (var viewer in viewers)
593 wakaba 1.12 sendMapData(viewers[viewer].port.postMessage);
594 wakaba 1.8 break;
595     case 'txt ':
596     var name = event.target._name;
597 wakaba 1.14 var message = event.data.substr(4);
598 wakaba 1.8 for (var viewer in viewers)
599     viewers[viewer].port.postMessage('txt ' + name + ' ' + message);
600     break;
601     case 'msg ':
602     var party1 = event._data;
603 wakaba 1.14 var party2 = viewers[event.data.substr(4).split(' ', 1)];
604 wakaba 1.8 if (party2) {
605     var channel = new MessageChannel();
606 wakaba 1.24 party1.port.postMessage('msg ' + party2.name, [channel.port1]);
607     party2.port.postMessage('msg ' + party1.name, [channel.port2]);
608 wakaba 1.8 }
609     break;
610     }
611     }</pre>
612    
613 wakaba 1.24 <p><strong>Connecting to multiple pages</strong>. The script uses
614     the <code title=handler-SharedWorkerGlobalScope-onconnect><a href=#handler-sharedworkerglobalscope-onconnect>onconnect</a></code>
615     event listener to listen for multiple connections.</p>
616    
617     <p><strong>Direct channels</strong>. When the worker receives a
618     "msg" message from one viewer naming another viewer, it sets up a
619     direct connection between the two, so that the two viewers can
620     communicate directly without the worker having to proxy all the
621     messages.</p>
622    
623     <p><a href=http://www.whatwg.org/demos/workers/multiviewer/page.html>View this example online</a>.</p>
624 wakaba 1.8
625    
626 wakaba 1.14 <h4 id=delegation><span class=secno>1.2.5 </span>Delegation</h4>
627 wakaba 1.8
628 wakaba 1.24 <p><em>This section is non-normative.</em></p>
629 wakaba 1.8
630     <p>With multicore CPUs becoming prevalent, one way to obtain better
631 wakaba 1.24 performance is to split computationally expensive tasks amongst
632     multiple workers. In this example, a computationally expensive task
633     that is to be performed for every number from 1 to 10,000,000 is
634     farmed out to ten subworkers.</p>
635    
636     <p>The main page is as follows, it just reports the result:</p>
637    
638     <pre>&lt;!DOCTYPE HTML&gt;
639     &lt;html&gt;
640     &lt;head&gt;
641     &lt;title&gt;Worker example: One-core computation&lt;/title&gt;
642     &lt;/head&gt;
643     &lt;body&gt;
644     &lt;p&gt;The highest prime number discovered so far is: &lt;output id="result"&gt;&lt;/output&gt;&lt;/p&gt;
645     &lt;script&gt;
646 wakaba 1.12 var worker = new Worker('worker.js');
647     worker.onmessage = function (event) {
648 wakaba 1.14 document.getElementById('result').textContent = event.data;
649 wakaba 1.8 };
650 wakaba 1.24 &lt;/script&gt;
651     &lt;/body&gt;
652     &lt;/html&gt;</pre>
653 wakaba 1.8
654 wakaba 1.24 <p>The worker itself is as follows:</p>
655 wakaba 1.8
656     <pre>// settings
657     var num_workers = 10;
658     var items_per_worker = 1000000;
659    
660     // start the workers
661     var result = 0;
662     var pending_workers = num_workers;
663     for (var i = 0; i &lt; num_workers; i += 1) {
664 wakaba 1.12 var worker = new Worker('core.js');
665     worker.postMessage(i * items_per_worker);
666     worker.postMessage((i+1) * items_per_worker);
667     worker.onmessage = storeResult;
668 wakaba 1.8 }
669    
670     // handle the results
671     function storeResult(event) {
672 wakaba 1.14 result += 1*event.data;
673 wakaba 1.8 pending_workers -= 1;
674     if (pending_workers &lt;= 0)
675 wakaba 1.12 postMessage(result); // finished!
676 wakaba 1.8 }</pre>
677    
678 wakaba 1.24 <p>It consists of a loop to start the subworkers, and then a handler
679     that waits for all the subworkers to respond.</p>
680 wakaba 1.8
681 wakaba 1.24 <p>The subworkers are implemented as follows:</p>
682 wakaba 1.8
683     <pre>var start;
684     onmessage = getStart;
685     function getStart(event) {
686 wakaba 1.14 start = 1*event.data;
687 wakaba 1.8 onmessage = getEnd;
688     }
689    
690     var end;
691     function getEnd(event) {
692 wakaba 1.14 end = 1*event.data;
693 wakaba 1.8 onmessage = null;
694 wakaba 1.16 work();
695 wakaba 1.8 }
696    
697 wakaba 1.16 function work() {
698 wakaba 1.8 var result = 0;
699     for (var i = start; i &lt; end; i += 1) {
700     // perform some complex calculation here
701     result += 1;
702     }
703 wakaba 1.12 postMessage(result);
704     close();
705 wakaba 1.8 }</pre>
706    
707 wakaba 1.24 <p>They receive two numbers in two events, perform the computation
708     for the range of numbers thus specified, and then report the result
709     back to the parent.</p>
710 wakaba 1.8
711 wakaba 1.24 <p><a href=http://www.whatwg.org/demos/workers/multicore/page.html>View this example online</a>.</p>
712 wakaba 1.8
713 wakaba 1.11
714 wakaba 1.24 <h4 id=providing-libraries><span class=secno>1.2.6 </span>Providing libraries</h4>
715 wakaba 1.11
716 wakaba 1.24 <p><em>This section is non-normative.</em></p>
717 wakaba 1.11
718 wakaba 1.24 <p>Suppose that a cryptography library is made available that
719     provides three tasks:</p>
720 wakaba 1.11
721 wakaba 1.24 <dl><dt>Generate a public/private key pair</dt>
722 wakaba 1.11
723 wakaba 1.24 <dd>Takes a port, on which it will send two messages, first the
724     public key and then the private key.</dd>
725 wakaba 1.11
726 wakaba 1.24 <dt>Given a plaintext and a public key, return the corresponding cyphertext</dt>
727 wakaba 1.11
728 wakaba 1.24 <dd>Takes a port, to which any number of messages can be sent, the
729     first giving the public key, and the remainder giving the
730     plaintext, each of which is encrypted and then sent on that same
731     channel as the cyphertext. The user can close the port when it is
732     done encrypting content.</dd>
733 wakaba 1.11
734 wakaba 1.24 <dt>Given a cyphertext and a private key, return the corresponding plaintext</dt>
735 wakaba 1.11
736 wakaba 1.24 <dd>Takes a port, to which any number of messages can be sent, the
737     first giving the private key, and the remainder giving the
738     cyphertext, each of which is decrypted and then sent on that same
739     channel as the plaintext. The user can close the port when it is
740     done decrypting content.</dd>
741    
742     </dl><p>The library itself is as follows:</p>
743 wakaba 1.11
744     <pre>function handleMessage(e) {
745 wakaba 1.14 if (e.data == "genkeys")
746 wakaba 1.24 genkeys(e.ports[0]);
747 wakaba 1.14 else if (e.data == "encrypt")
748 wakaba 1.24 encrypt(e.ports[0]);
749 wakaba 1.14 else if (e.data == "decrypt")
750 wakaba 1.24 decrypt(e.ports[0]);
751 wakaba 1.11 }
752    
753     function genkeys(p) {
754     var keys = _generateKeyPair();
755     p.postMessage(keys[0]);
756     p.postMessage(keys[1]);
757     }
758    
759     function encrypt(p) {
760     var key, state = 0;
761     p.onmessage = function (e) {
762     if (state == 0) {
763 wakaba 1.14 key = e.data;
764 wakaba 1.11 state = 1;
765     } else {
766 wakaba 1.14 p.postMessage(_encrypt(key, e.data));
767 wakaba 1.11 }
768     };
769     }
770    
771     function decrypt(p) {
772     var key, state = 0;
773     p.onmessage = function (e) {
774     if (state == 0) {
775 wakaba 1.14 key = e.data;
776 wakaba 1.11 state = 1;
777     } else {
778 wakaba 1.14 p.postMessage(_decrypt(key, e.data));
779 wakaba 1.11 }
780     };
781     }
782    
783 wakaba 1.12 // support being used as a shared worker as well as a dedicated worker
784     if (this.onmessage) // dedicated worker
785     onmessage = handleMessage;
786     else // shared worker
787     onconnect = function (e) { e.port.onmessage = handleMessage; }
788 wakaba 1.11
789    
790     // the "crypto" functions:
791    
792     function _generateKeyPair() {
793     return [Math.random(), Math.random()];
794     }
795    
796     function _encrypt(k, s) {
797     return 'encrypted-' + k + ' ' + s;
798     }
799    
800     function _decrypt(k, s) {
801     return s.substr(s.indexOf(' ')+1);
802     }</pre>
803    
804 wakaba 1.24 <p>Note that the crypto functions here are just stubs and don't do
805     real cryptography.</p>
806 wakaba 1.11
807 wakaba 1.24 <p>This library could be used as follows:</p>
808 wakaba 1.11
809 wakaba 1.24 <pre>&lt;!DOCTYPE HTML&gt;
810     &lt;html&gt;
811     &lt;head&gt;
812     &lt;title&gt;Worker example: Crypto library&lt;/title&gt;
813     &lt;script&gt;
814 wakaba 1.12 var crytoLib = new Worker('libcrypto-v1.js'); // or could use 'libcrypto-v2.js'
815 wakaba 1.11 function getKeys() {
816     var state = 0;
817 wakaba 1.12 cryptoLib.startConversation("genkeys").onmessage = function (e) {
818 wakaba 1.11 if (state == 0)
819 wakaba 1.14 document.getElementById('public').value = e.data;
820 wakaba 1.11 else if (state == 1)
821 wakaba 1.14 document.getElementById('private').value = e.data;
822 wakaba 1.11 state += 1;
823     };
824     }
825     function enc() {
826 wakaba 1.12 var port = cryptoLib.startConversation("encrypt");
827     port.postMessage(document.getElementById('public').value);
828     port.postMessage(document.getElementById('input').value);
829     port.onmessage = function (e) {
830 wakaba 1.14 document.getElementById('input').value = e.data;
831 wakaba 1.12 port.close();
832 wakaba 1.11 };
833     }
834     function dec() {
835 wakaba 1.12 var port = cryptoLib.startConversation("decrypt");
836     port.postMessage(document.getElementById('private').value);
837     port.postMessage(document.getElementById('input').value);
838     port.onmessage = function (e) {
839 wakaba 1.14 document.getElementById('input').value = e.data;
840 wakaba 1.12 port.close();
841 wakaba 1.11 };
842     }
843 wakaba 1.24 &lt;/script&gt;
844     &lt;style&gt;
845 wakaba 1.11 textarea { display: block; }
846 wakaba 1.24 &lt;/style&gt;
847     &lt;/head&gt;
848     &lt;body onload="getKeys()"&gt;
849     &lt;fieldset&gt;
850     &lt;legend&gt;Keys&lt;/legend&gt;
851     &lt;p&gt;&lt;label&gt;Public Key: &lt;textarea id="public"&gt;&lt;/textarea&gt;&lt;/label&gt;&lt;/p&gt;
852     &lt;p&gt;&lt;label&gt;Private Key: &lt;textarea id="private"&gt;&lt;/textarea&gt;&lt;/label&gt;&lt;/p&gt;
853     &lt;/fieldset&gt;
854     &lt;p&gt;&lt;label&gt;Input: &lt;textarea id="input"&gt;&lt;/textarea&gt;&lt;/label&gt;&lt;/p&gt;
855     &lt;p&gt;&lt;button onclick="enc()"&gt;Encrypt&lt;/button&gt; &lt;button onclick="dec()"&gt;Decrypt&lt;/button&gt;&lt;/p&gt;
856     &lt;/body&gt;
857     &lt;/html&gt;</pre>
858 wakaba 1.11
859 wakaba 1.24 <p>A later version of the API, though, might want to offload all the
860     crypto work onto subworkers. This could be done as follows:</p>
861 wakaba 1.11
862     <pre>function handleMessage(e) {
863 wakaba 1.14 if (e.data == "genkeys")
864 wakaba 1.24 genkeys(e.ports[0]);
865 wakaba 1.14 else if (e.data == "encrypt")
866 wakaba 1.24 encrypt(e.ports[0]);
867 wakaba 1.14 else if (e.data == "decrypt")
868 wakaba 1.24 decrypt(e.ports[0]);
869 wakaba 1.11 }
870    
871     function genkeys(p) {
872 wakaba 1.12 var generator = new Worker('libcrypto-v2-generator.js');
873 wakaba 1.24 generator.postMessage('', [p]);
874 wakaba 1.11 }
875    
876     function encrypt(p) {
877     p.onmessage = function (e) {
878 wakaba 1.14 var key = e.data;
879 wakaba 1.12 var encryptor = new Worker('libcrypto-v2-encryptor.js');
880 wakaba 1.24 encryptor.postMessage(key, [p]);
881 wakaba 1.11 };
882     }
883    
884     function encrypt(p) {
885     p.onmessage = function (e) {
886 wakaba 1.14 var key = e.data;
887 wakaba 1.12 var decryptor = new Worker('libcrypto-v2-decryptor.js');
888 wakaba 1.24 decryptor.postMessage(key, [p]);
889 wakaba 1.11 };
890     }
891    
892 wakaba 1.12 // support being used as a shared worker as well as a dedicated worker
893     if (this.onmessage) // dedicated worker
894     onmessage = handleMessage;
895     else // shared worker
896 wakaba 1.24 onconnect = function (e) { e.ports[0].onmessage = handleMessage };
897 wakaba 1.11 </pre>
898    
899 wakaba 1.24 <p>The little subworkers would then be as follows.</p>
900 wakaba 1.11
901 wakaba 1.24 <p>For generating key pairs:</p>
902 wakaba 1.11
903 wakaba 1.12 <pre>onmessage = function (e) {
904     var k = _generateKeyPair();
905 wakaba 1.24 e.ports[0].postMessage(k[0]);
906     e.ports[0].postMessage(k[1]);
907 wakaba 1.11 close();
908     }
909 wakaba 1.12
910     function _generateKeyPair() {
911     return [Math.random(), Math.random()];
912     }</pre>
913 wakaba 1.11
914 wakaba 1.24 <p>For encrypting:</p>
915 wakaba 1.11
916 wakaba 1.12 <pre>onmessage = function (e) {
917 wakaba 1.14 var key = e.data;
918 wakaba 1.24 e.ports[0].onmessage = function (e) {
919 wakaba 1.14 var s = e.data;
920 wakaba 1.12 postMessage(_encrypt(key, s));
921 wakaba 1.11 }
922 wakaba 1.24 e.ports[0].onclose = function (e) {
923 wakaba 1.11 close();
924     }
925 wakaba 1.12 }
926    
927     function _encrypt(k, s) {
928     return 'encrypted-' + k + ' ' + s;
929 wakaba 1.11 }</pre>
930    
931 wakaba 1.24 <p>For decrypting:</p>
932 wakaba 1.11
933 wakaba 1.12 <pre>onmessage = function (e) {
934 wakaba 1.14 var key = e.data;
935 wakaba 1.24 e.ports[0].onmessage = function (e) {
936 wakaba 1.14 var s = e.data;
937 wakaba 1.12 postMessage(_decrypt(key, s));
938 wakaba 1.11 }
939 wakaba 1.24 e.ports[0].onclose = function (e) {
940 wakaba 1.11 close();
941     }
942 wakaba 1.12 }
943    
944     function _decrypt(k, s) {
945     return s.substr(s.indexOf(' ')+1);
946 wakaba 1.11 }</pre>
947    
948 wakaba 1.24 <p>Notice how the users of the API don't have to even know that this
949     is happening &mdash; the API hasn't changed; the library can
950     delegate to subworkers without changing its API, even though it is
951     accepting data using message channels.</p>
952    
953     <p><a href=http://www.whatwg.org/demos/workers/crypto/page.html>View this example online</a>.</p>
954    
955    
956 wakaba 1.11
957    
958 wakaba 1.24 <h2 id=conformance-requirements><span class=secno>2 </span>Conformance requirements</h2>
959 wakaba 1.1
960     <p>All diagrams, examples, and notes in this specification are
961 wakaba 1.24 non-normative, as are all sections explicitly marked non-normative.
962     Everything else in this specification is normative.</p>
963 wakaba 1.1
964     <p>The key words "MUST", "MUST NOT", "REQUIRED", <!--"SHALL", "SHALL
965 wakaba 1.24 NOT",--> "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and
966     "OPTIONAL" in the normative parts of this document are to be
967     interpreted as described in RFC2119. For readability, these words do
968     not appear in all uppercase letters in this specification. <a href=#refsRFC2119>[RFC2119]</a></p>
969    
970     <p>Requirements phrased in the imperative as part of algorithms
971     (such as "strip any leading space characters" or "return false and
972     abort these steps") are to be interpreted with the meaning of the
973     key word ("must", "should", "may", etc) used in introducing the
974     algorithm.</p>
975    
976     <p>Some conformance requirements are phrased as requirements on
977     attributes, methods or objects. Such requirements are to be
978     interpreted as requirements on user agents.</p>
979    
980     <p>Conformance requirements phrased as algorithms or specific steps
981     may be implemented in any manner, so long as the end result is
982     equivalent. (In particular, the algorithms defined in this
983     specification are intended to be easy to follow, and not intended to
984     be performant.)</p>
985    
986     <p>The only conformance class defined by this specification is user
987     agents.</p>
988    
989     <p>User agents may impose implementation-specific limits on
990     otherwise unconstrained inputs, e.g. to prevent denial of service
991     attacks, to guard against running out of memory, or to work around
992     platform-specific limitations.</p>
993 wakaba 1.1
994    
995 wakaba 1.24 <h3 id=dependencies><span class=secno>2.1 </span>Dependencies</h3>
996 wakaba 1.1
997 wakaba 1.24 <p>This specification relies on several other underlying
998     specifications.</p>
999    
1000     <dl><dt>HTML5</dt>
1001 wakaba 1.1
1002     <dd>
1003    
1004 wakaba 1.24 <p>Many fundamental concepts from HTML5 are used by this
1005     specification. <a href=#refsHTML5>[HTML5]</a></p>
1006    
1007     </dd>
1008    
1009     <dt>WebIDL</dt>
1010 wakaba 1.1
1011     <dd>
1012    
1013 wakaba 1.24 <p>The IDL blocks in this specification use the semantics of the
1014     WebIDL specification. <a href=#refsWebIDL>[WebIDL]</a></p>
1015    
1016     </dd>
1017 wakaba 1.1
1018 wakaba 1.24 </dl><h2 id=terminology><span class=secno>3 </span>Terminology</h2>
1019    
1020     <p>The construction "a <code title="">Foo</code> object", where
1021     <code title="">Foo</code> is actually an interface, is sometimes
1022     used instead of the more accurate "an object implementing the
1023     interface <code title="">Foo</code>".</p>
1024    
1025     <p>The term DOM is used to refer to the API set made available to
1026     scripts in Web applications, and does not necessarily imply the
1027     existence of an actual <code>Document</code> object or of any other
1028     <code>Node</code> objects as defined in the DOM Core
1029     specifications. <a href=#refsDOM3CORE>[DOM3CORE]</a></p>
1030    
1031     <p>A DOM attribute is said to be <em>getting</em> when its value is
1032     being retrieved (e.g. by author script), and is said to be
1033     <em>setting</em> when a new value is assigned to it.</p>
1034    
1035    
1036    
1037     <h2 id=infrastructure><span class=secno>4 </span>Infrastructure</h2>
1038    
1039     <p>There are two kinds of workers; dedicated workers, and shared
1040     workers. Dedicated workers, once created, and are linked to their
1041     creator; but message ports can be used to communicate from a
1042     dedicated worker to multiple other browsing contexts or
1043     workers. Shared workers, on the other hand, are named, and once
1044     created any script running in the same <span>origin</span> can
1045     obtain a reference to that worker and communicate with it.</p>
1046    
1047    
1048     <h3 id=the-global-scope><span class=secno>4.1 </span>The global scope</h3>
1049    
1050     <p>The global scope is the "inside" of a worker.</p>
1051    
1052     <h4 id=the-workerglobalscope-abstract-interface><span class=secno>4.1.1 </span>The <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> abstract interface</h4>
1053    
1054     <pre class=idl>interface <dfn id=workerglobalscope>WorkerGlobalScope</dfn> {
1055     readonly attribute <a href=#workerglobalscope>WorkerGlobalScope</a> <a href=#dom-workerglobalscope-self title=dom-WorkerGlobalScope-self>self</a>;
1056     readonly attribute <a href=#workerlocation>WorkerLocation</a> <a href=#dom-workerglobalscope-location title=dom-WorkerGlobalScope-location>location</a>;
1057     // also implements everything on <a href=#workerutils>WorkerUtils</a>
1058    
1059     void <a href=#dom-workerglobalscope-close title=dom-WorkerGlobalScope-close>close</a>();
1060     attribute <span>EventListener</span> <a href=#handler-workerglobalscope-onclose title=handler-WorkerGlobalScope-onclose>onclose</a>;
1061     attribute <span>EventListener</span> <a href=#handler-workerglobalscope-onerror title=handler-WorkerGlobalScope-onerror>onerror</a>;
1062 wakaba 1.3 };</pre>
1063    
1064 wakaba 1.24 <p>Objects implementing the <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> interface
1065     must also implement the <code>EventTarget</code> interface.</p>
1066    
1067     <p>The <dfn id=dom-workerglobalscope-self title=dom-WorkerGlobalScope-self><code>self</code></dfn> attribute
1068     must return the <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object itself.</p>
1069    
1070     <p>The <dfn id=dom-workerglobalscope-location title=dom-WorkerGlobalScope-location><code>location</code></dfn>
1071     attribute must return the <code><a href=#workerlocation>WorkerLocation</a></code> object created
1072     for the <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object when the worker was
1073     created. It represents the <span>absolute URL</span> of the script
1074     that was used to initialize the worker.</p>
1075    
1076     <hr><p>When a script invokes the <dfn id=dom-workerglobalscope-close title=dom-WorkerGlobalScope-close><code>close()</code></dfn> method on
1077     a <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object, the user agent must run the
1078     following steps:</p>
1079    
1080     <ol><li><p><span>Queue a task</span> to <span>fire a simple
1081     event</span> called <code title=event-close>close</code> at the
1082     <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object.</li>
1083 wakaba 1.12
1084 wakaba 1.24 <li><p>Set the worker's <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object's
1085     <a href=#dom-workerglobalscope-closing title=dom-WorkerGlobalScope-closing>closing</a> flag to
1086     true.</li>
1087    
1088     <li><p>For each <code>MessagePort</code> object that is entangled
1089     with another port and that has one (but only one) port whose owner
1090     is the <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object on which the method
1091     was invoked (this would include, for instance, the implicit port in
1092     used for dedicated workers), unentangle the two ports.</li>
1093    
1094     </ol><p>The following are the <span>event handler DOM attributes</span>
1095     that must be supported by objects implementing the
1096     <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> interface:</p>
1097    
1098     <dl><dt><dfn id=handler-workerglobalscope-onclose title=handler-WorkerGlobalScope-onclose><code>onclose</code></dfn></dt>
1099    
1100     <dd><p>Must be invoked whenever a <code title=event-close>close</code> event is targeted at or bubbles
1101     through the <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object.</dd>
1102 wakaba 1.12
1103    
1104 wakaba 1.24 <dt><dfn id=handler-workerglobalscope-onerror title=handler-WorkerGlobalScope-onerror><code>onerror</code></dfn></dt>
1105 wakaba 1.4
1106 wakaba 1.24 <dd><p>Must be invoked whenever an <code title=event-error>error</code> event is targeted at or bubbles
1107     through the <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object.</dd>
1108 wakaba 1.20
1109 wakaba 1.24 </dl><h4 id=dedicated-workers-and-the-dedicatedworkerglobalscope-interface><span class=secno>4.1.2 </span>Dedicated workers and the <code><a href=#dedicatedworkerglobalscope>DedicatedWorkerGlobalScope</a></code> interface</h4>
1110 wakaba 1.20
1111 wakaba 1.22 <!-- the XXX below is for collapsing this interface onto WorkerGlobalScope so it looks like just one interface - the inheritance is a spec fiction only -->
1112 wakaba 1.24 <pre class=idl>[NoInterfaceObject, XXX] interface <dfn id=dedicatedworkerglobalscope>DedicatedWorkerGlobalScope</dfn> : <a href=#workerglobalscope>WorkerGlobalScope</a> {
1113     void <a href=#dom-dedicatedworkerglobalscope-postmessage title=dom-DedicatedWorkerGlobalScope-postMessage>postMessage</a>(in any message, [Optional] in <span>MessagePortArray</span> ports);<!--
1114 wakaba 1.22 <span>MessagePort</span> <span title="dom-DedicatedWorkerGlobalScope-startConversation">startConversation</span>(in any message);-->
1115 wakaba 1.24 attribute <span>EventListener</span> <a href=#handler-dedicatedworkerglobalscope-onmessage title=handler-DedicatedWorkerGlobalScope-onmessage>onmessage</a>;
1116 wakaba 1.12 };</pre>
1117    
1118 wakaba 1.24 <p><code><a href=#dedicatedworkerglobalscope>DedicatedWorkerGlobalScope</a></code> objects act as if they
1119     had an implicit <code>MessagePort</code> associated with them. This
1120     port is part of a channel that is set up when the worker is created,
1121     but it is not exposed. This object must never be garbage collected
1122     before the <code><a href=#dedicatedworkerglobalscope>DedicatedWorkerGlobalScope</a></code> object.</p>
1123    
1124     <p>All messages received by that port must immediately be
1125     retargetted at the <code><a href=#dedicatedworkerglobalscope>DedicatedWorkerGlobalScope</a></code>
1126     object.</p>
1127 wakaba 1.12
1128 wakaba 1.24 <p>The <dfn id=dom-dedicatedworkerglobalscope-postmessage title=dom-DedicatedWorkerGlobalScope-postMessage><code>postMessage()</code></dfn><!--
1129 wakaba 1.14 and <dfn
1130     title="dom-DedicatedWorkerGlobalScope-startConversation"><code>startConversation()</code></dfn>-->
1131 wakaba 1.24 method<!--s (startConversation)--> on
1132     <code><a href=#dedicatedworkerglobalscope>DedicatedWorkerGlobalScope</a></code> objects must act as if, when
1133     invoked, it<!--/they (startConversation)--> immediately invoked the
1134     method of the same name on the port, with the same arguments, and
1135     returned the same return value.</p>
1136    
1137     <p>The following are the <span>event handler DOM attributes</span>
1138     that must be supported by objects implementing the
1139     <code><a href=#dedicatedworkerglobalscope>DedicatedWorkerGlobalScope</a></code> interface:</p>
1140    
1141     <dl><dt><dfn id=handler-dedicatedworkerglobalscope-onmessage title=handler-DedicatedWorkerGlobalScope-onmessage><code>onmessage</code></dfn></dt>
1142    
1143     <dd><p>Must be invoked whenever a <code title=event-DedicatedWorkerGlobalScope-message>message</code> event is targeted
1144     at or bubbles through the <code><a href=#dedicatedworkerglobalscope>DedicatedWorkerGlobalScope</a></code> object.</dd>
1145    
1146     </dl><h4 id=shared-workers-and-the-sharedworkerglobalscope-inteface><span class=secno>4.1.3 </span>Shared workers and the <code><a href=#sharedworkerglobalscope>SharedWorkerGlobalScope</a></code> inteface</h4>
1147 wakaba 1.4
1148 wakaba 1.22 <!-- the XXX below is for collapsing this interface onto WorkerGlobalScope so it looks like just one interface - the inheritance is a spec fiction only -->
1149 wakaba 1.24 <pre class=idl>[NoInterfaceObject, XXX] interface <dfn id=sharedworkerglobalscope>SharedWorkerGlobalScope</dfn> : <a href=#workerglobalscope>WorkerGlobalScope</a> {
1150     readonly attribute DOMString <a href=#dom-sharedworkerglobalscope-name title=dom-SharedWorkerGlobalScope-name>name</a>;
1151     attribute <span>EventListener</span> <a href=#handler-sharedworkerglobalscope-onconnect title=handler-SharedWorkerGlobalScope-onconnect>onconnect</a>;
1152     };</pre>
1153    
1154     <p>Shared workers receive message ports through <code title=event-WorkerGlobalScope-connect>connect</code> events on
1155     their global object for each connection.</p>
1156    
1157     <p>The <dfn id=dom-sharedworkerglobalscope-name title=dom-SharedWorkerGlobalScope-name><code>name</code></dfn>
1158     attribute must return the value it was assigned when the
1159     <code><a href=#sharedworkerglobalscope>SharedWorkerGlobalScope</a></code> object was created by the
1160     "<a href=#run-a-worker>run a worker</a>" algorithm. Its value represents the name
1161     that can be used to obtain a reference to the worker using the
1162     <code><a href=#sharedworker>SharedWorker</a></code> constructor.</p>
1163    
1164     <p>The following are the <span>event handler DOM attributes</span>
1165     that must be supported by objects implementing the
1166     <code><a href=#sharedworkerglobalscope>SharedWorkerGlobalScope</a></code> interface:</p>
1167    
1168     <dl><dt><dfn id=handler-sharedworkerglobalscope-onconnect title=handler-SharedWorkerGlobalScope-onconnect><code>onconnect</code></dfn></dt>
1169    
1170     <dd><p>Must be invoked whenever a <code title=event-SharedWorkerGlobalScope-connect>connect</code> event is targeted
1171     at or bubbles through the <code><a href=#sharedworkerglobalscope>SharedWorkerGlobalScope</a></code> object.</dd>
1172    
1173     </dl><h3 id=base-urls-and-origins-of-workers><span class=secno>4.2 </span>Base URLs and origins of workers</h3>
1174    
1175     <p>Both the <span>origin</span> and <span>effective script
1176     origin</span> of scripts running in workers are the
1177     <span>origin</span> of the <span>absolute URL</span> given in that
1178     the worker's <code title=dom-WorkerGlobalScope-location><a href=#dom-workerglobalscope-location>location</a></code> attribute
1179     represents.</p>
1180    
1181    
1182     <h3 id=decoding-scripts><span class=secno>4.3 </span>Decoding scripts</h3>
1183    
1184     <p>When a user agent is to <dfn id=decode-a-script-resource>decode a script resource</dfn> to
1185     obtain its source in Unicode, it must run the following steps:</p>
1186    
1187     <ol><li>
1188    
1189     <p>Let <var title="">character encoding</var> be <i title="">unknown</i>.</p>
1190    
1191     </li>
1192    
1193     <li>
1194    
1195     <p>For each of the rows in the following table, starting with the
1196     first one and going down, if the resource has as many or more
1197     bytes available than the number of bytes in the first column, and
1198     the first bytes of the resource match the bytes given in the first
1199     column, then let <var title="">character encoding</var> be the
1200     encoding given in the cell in the second column of that row:</p>
1201    
1202     <!-- this table is present in several forms in this file; keep them in sync -->
1203     <table><thead><tr><th>Bytes in Hexadecimal
1204     <th>Encoding
1205     <tbody><!-- nobody uses this
1206     <tr>
1207     <td>00 00 FE FF
1208     <td>UTF-32BE
1209     <tr>
1210     <td>FF FE 00 00
1211     <td>UTF-32LE
1212     --><tr><td>FE FF
1213     <td>UTF-16BE
1214     <tr><td>FF FE
1215     <td>UTF-16LE
1216     <tr><td>EF BB BF
1217     <td>UTF-8
1218     <!-- nobody uses this
1219     <tr>
1220     <td>DD 73 66 73
1221     <td>UTF-EBCDIC
1222     -->
1223     </table><p class=note>This step looks for Unicode Byte Order Marks
1224     (BOMs).</p>
1225    
1226     </li>
1227 wakaba 1.12
1228 wakaba 1.24 <li>
1229    
1230     <p>If <var title="">character encoding</var> is still <i title="">unknown</i>, apply the <span>algorithm for extracting an
1231     encoding from a Content-Type</span> to the resource's <span title=Content-Type>Content Type metadata</span>; if this returns
1232     an encoding, and the user agent supports that encoding, then let
1233     <var title="">character encoding</var> be that encoding.</p>
1234    
1235     </li>
1236    
1237     <li>
1238    
1239     <p>If <var title="">character encoding</var> is still <i title="">unknown</i>, then let <var title="">character
1240     encoding</var> be UTF-8.</p>
1241    
1242     </li>
1243    
1244     <li>
1245    
1246     <p>Convert the resource to Unicode using the character encoding
1247     given by <var title="">character encoding</var>.</p>
1248    
1249     <p>Return the text that is so obtained.</p>
1250    
1251     </li>
1252 wakaba 1.12
1253 wakaba 1.24 </ol><h3 id=the-event-loop><span class=secno>4.4 </span>The event loop</h3>
1254 wakaba 1.12
1255 wakaba 1.24 <p>Each <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object is asssociated with a
1256     <span>event loop</span>. This <span>event loop</span> has no
1257     associated <span>browsing context</span>, and its <span title="task
1258     queue">task queues</span> only have events, callbacks, and
1259     networking activity as <span title=concept-task>tasks</span>. The
1260     processing model of these <span title="event loop">event
1261     loops</span> is defined below in the <a href=#run-a-worker>run a worker</a>
1262     algorithm.</p>
1263    
1264     <p>Each <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object also has a <dfn id=dom-workerglobalscope-closing title=dom-WorkerGlobalScope-closing>closing</dfn> flag, which must
1265     initially be false, but which can get set to true by the algorithms
1266     in the processing model section below.</p>
1267    
1268     <p>Once the <code><a href=#workerglobalscope>WorkerGlobalScope</a></code>'s <a href=#dom-workerglobalscope-closing title=dom-WorkerGlobalScope-closing>closing</a> flag is set to
1269     true, the <span>event loop</span>'s <span title="task queue">task
1270     queues</span> must discard any further <span title=concept-task>tasks</span> that would be added to them (tasks
1271     already on the queue are unaffected unless otherwise
1272     specified). Effectively, once the <a href=#dom-workerglobalscope-closing title=dom-WorkerGlobalScope-closing>closing</a> flag is true,
1273     timers stop firing, notifications for all pending asynchronous
1274     operations are dropped, etc.</p>
1275    
1276    
1277     <h3 id="the-worker's-ports"><span class=secno>4.5 </span>The worker's ports</h3>
1278    
1279     <p>Workers communicate with other workers and with <span title="browsing context">browsing contexts</span> through <span title="channel messaging">message channels</span> and their
1280     <code>MessagePort</code> objects.</p>
1281    
1282     <p>Each <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> <var title="">worker global
1283     scope</var> has a list of <dfn id="the-worker's-ports-0">the worker's ports</dfn>, which
1284     consists of all the <code>MessagePort</code> objects that are
1285     entangled with another port and that have one (but only one) port
1286     owned by <var title="">worker global scope</var>. This list includes
1287     <!--all the <code>MessagePort</code> objects that are in events
1288 wakaba 1.18 pending in the <span>event loop</span>, as well as (commented out
1289     because in practice it makes no difference either way as far as I
1290     can tell, and it would be hard to strictly implement since these
1291 wakaba 1.24 ports might not yet be across the thread boundary)--> the implicit
1292     <code>MessagePort</code> in the case of <a href=#dedicatedworkerglobalscope title=DedicatedWorkerGlobalScope>dedicated workers</a>.</p>
1293    
1294     <hr><p>A worker is said to be a <dfn id=permissible-worker>permissible worker</dfn> if
1295     either:</p>
1296    
1297     <ul><li>at some point past or present a <code>MessagePort</code> owned
1298     by the worker was entangled with a <code>MessagePort</code> <var title="">p</var> whose owner is a <code>Window</code> object whose
1299     <span>active document</span> is the <code>Document</code> that was
1300     that <span>browsing context</span>'s <span>active document</span>
1301     when <var title="">p</var> was created, and that
1302     <code>Document</code> is <span>fully active</span>, or</li>
1303    
1304     <li>at some point past or present a <code>MessagePort</code> owned
1305     by the worker was entangled with a <code>MessagePort</code> owned
1306     by another worker that is currently a <a href=#permissible-worker>permissible
1307     worker</a>.</li>
1308    
1309     </ul><hr><p>A worker is said to be a <dfn id=protected-worker>protected worker</dfn> if
1310     either:</p>
1311    
1312     <ul><li>it has outstanding timers, database transactions, or network
1313     connections, and is a <a href=#permissible-worker>permissible worker</a>, or</li>
1314    
1315     <li>there is a <a href=#protected-worker>protected worker</a> that at some point
1316     past or present owned a <code>MessagePort</code> that was entangled
1317     with a <code>MessagePort</code> owned by this worker.</li>
1318    
1319     </ul><hr><p>A worker is said to be an <dfn id=active-needed-worker>active needed worker</dfn> if either:
1320    
1321     <ul><li>the worker is a <a href=#protected-worker>protected worker</a>, or</li>
1322    
1323     <li>at least one of the <a href="#the-worker's-ports-0">the worker's ports</a> is
1324     entangled with a <code>MessagePort</code> <var title="">p</var>
1325     whose owner is a <code>Window</code> object whose <span>active
1326     document</span> is the <code>Document</code> that was that
1327     <span>browsing context</span>'s <span>active document</span> when
1328     that <code>MessagePort</code> <var title="">p</var> was created,
1329     and that <code>Document</code> is <span>fully active</span>,
1330     or</li>
1331    
1332     <li>at least one of the <a href="#the-worker's-ports-0">the worker's ports</a> has an
1333     entangled <code>MessagePort</code> owned by a
1334     <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object that is itself an
1335     <a href=#active-needed-worker>active needed worker</a>.</li>
1336    
1337     </ul><hr><p>A worker is said to be a <dfn id=suspendable-worker>suspendable worker</dfn> if it is
1338     not an <a href=#active-needed-worker>active needed worker</a> but either:</p>
1339    
1340     <ul><li>at least one of the <a href="#the-worker's-ports-0">the worker's ports</a> has an
1341     entangled <code>MessagePort</code> owned by a <code>Window</code>
1342     object, or</li>
1343    
1344     <li>at least one of the <a href="#the-worker's-ports-0">the worker's ports</a> has an
1345     entangled <code>MessagePort</code> owned by a
1346     <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object that is itself a <span>needed
1347     worker</span>.</li>
1348    
1349     </ul><h3 id=processing-model><span class=secno>4.6 </span>Processing model</h3>
1350    
1351     <p>When a user agent is to <dfn id=run-a-worker>run a worker</dfn> for a script with
1352     <span>URL</span> <var title="">url</var>, a browsing context <var title="">owner browsing context</var>, and with global scope <var title="">worker global scope</var>, it must run the following
1353     steps:</p>
1354    
1355     <ol><li>
1356    
1357     <p>Create a completely separate and parallel execution environment
1358     (i.e. a separate thread or process or equivalent construct), and
1359     run the rest of these steps asychronously in that context.</p>
1360    
1361     </li>
1362 wakaba 1.3
1363     <li>
1364 wakaba 1.13
1365 wakaba 1.24 <p>Attempt to <span>fetch</span> the resource identified by <var title="">url</var>.</p>
1366    
1367     <p>If the attempt fails, then for each <code><a href=#worker>Worker</a></code> or
1368     <code><a href=#sharedworker>SharedWorker</a></code> object associated with <var title="">worker global scope</var>, <span>queue a task</span> to
1369     <span>fire a simple event</span> called <code title=event-error>error</code> at that object. Abort these
1370     steps.</p>
1371    
1372     <p>If the attempt succeeds, then <a href=#decode-a-script-resource title="decode a script
1373     resource">decode the script resource</a> to obtain its <var title="">source</var>.</p>
1374 wakaba 1.4
1375 wakaba 1.18 <p>Let <var title="">language</var> be JavaScript.</p>
1376 wakaba 1.4
1377 wakaba 1.24 <p class=note>As with <code>script</code> elements, the MIME
1378     type of the script is ignored. Unlike with <code>script</code>
1379     elements, there is no way to override the type. It's always
1380     assumed to be JavaScript.</p> <!-- XXX people will complain about
1381 wakaba 1.4 this. I guess we might want to examine the MIME type... -->
1382 wakaba 1.24
1383     </li>
1384 wakaba 1.4
1385     <li>
1386 wakaba 1.8
1387 wakaba 1.24 <p>A new <span title=concept-script>script</span> is now
1388     created, as follows.</p>
1389    
1390     <p>Create a new <span>script execution environment</span>
1391     set up as appropriate for the scripting language <var title="">language</var>.</p>
1392 wakaba 1.18
1393     <p>Parse/compile/initialize <var title="">source</var> using that
1394 wakaba 1.24 <span>script execution environment</span>, as appropriate for <var title="">language</var>, and thus obtain a <span>list of code
1395     entry-points</span>; set the <i>initial code entry-point</i> to
1396     the entry-point for any executable code to be immediately run.</p>
1397    
1398     <p>Set the <span>script's global object</span> to <var title="">worker global scope</var>.</p>
1399    
1400     <p>Set the <span>script's browsing context</span> to <var title="">owner browsing context</var>.</p>
1401    
1402     <p>Set the <span>script's URL character encoding</span> to
1403     UTF-8. (This is just used for encoding non-ASCII characters in the
1404     query component of URLs.)</p>
1405 wakaba 1.18
1406     <p>Set the <span>script's base URL</span> to <var title="">url</var>.</p>
1407 wakaba 1.3
1408 wakaba 1.24 <p>Create a new <span>script group</span> and add the <span title=concept-script>script</span> to it.</p>
1409    
1410     </li>
1411 wakaba 1.3
1412     <li>
1413 wakaba 1.24
1414     <p><strong>Closing orphan workers</strong>: Start monitoring the
1415     worker such that as soon as it stops being either an <a href=#active-needed-worker>active
1416     needed worker</a> or a <a href=#suspendable-worker>suspendable worker</a>, <var title="">worker global scope</var>'s <a href=#dom-workerglobalscope-closing title=dom-WorkerGlobalScope-closing>closing</a> flag is set
1417     to true and <span title="queue a task">a task is queued</span> to
1418     <span>fire a simple event</span> called <code title=event-close>close</code> at <var title="">worker global
1419     scope</var>.</p>
1420    
1421     </li>
1422 wakaba 1.4
1423     <li>
1424 wakaba 1.24
1425     <p><strong>Suspending workers</strong>: Start monitoring the
1426     worker, such that whenever <var title="">worker global
1427     scope</var>'s <a href=#dom-workerglobalscope-closing title=dom-WorkerGlobalScope-closing>closing</a> flag is false
1428     and the worker is a <a href=#suspendable-worker>suspendable worker</a>, the user
1429     agent suspends execution of script in that worker until such time
1430     as either the <a href=#dom-workerglobalscope-closing title=dom-WorkerGlobalScope-closing>closing</a> flag switches
1431     to true or the worker stops being a <a href=#suspendable-worker>suspendable
1432     worker</a>.</p>
1433    
1434     </li>
1435 wakaba 1.4
1436     <li>
1437 wakaba 1.24
1438     <p><span title="jump to a code entry-point">Jump</span> to the
1439     <span title=concept-script>script</span>'s <i>initial code
1440     entry-point</i>, and let that run until it either returns, fails
1441     to catch an exception, or gets prematurely aborted by the
1442     "<a href=#kill-a-worker>kill a worker</a>" or "<a href=#terminate-a-worker>terminate a worker</a>"
1443     algorithms defined below.</p>
1444    
1445     <p class=note>If the script gets aborted by the "<a href=#kill-a-worker>kill a
1446     worker</a>" algorithm, then that same algorithm will cause
1447     there to only be a single <span title=concept-task>task</span>
1448     in the <span>event loop</span> at the next step, namely the task
1449     for the <code title=message-close>close</code> event. The
1450     "<a href=#terminate-a-worker>terminate a worker</a>" algorithm removes all the
1451     events.</p>
1452    
1453     </li>
1454 wakaba 1.4
1455     <li>
1456 wakaba 1.24
1457     <p><i title="">Event loop</i>: Wait until either there is a <span title=concept-task>task</span> in one of the <span>event
1458     loop</span>'s <span title="task queue">task queues</span> or <var title="">worker global scope</var>'s <a href=#dom-workerglobalscope-closing title=dom-WorkerGlobalScope-closing>closing</a> flag is set
1459     to true.</p>
1460    
1461     </li>
1462 wakaba 1.18
1463     <li>
1464 wakaba 1.24
1465     <p>Run the oldest task on one of the <span>event loop</span>'s
1466     <span title="task queue">task queues</span>, if any. The user
1467     agent may pick any <span>task queue</span>.</p>
1468    
1469     <p class=note>The handling of events or the execution of
1470     callbacks might get prematurely aborted by the "<a href=#kill-a-worker>kill a
1471     worker</a>" or "<a href=#terminate-a-worker>terminate a worker</a>" algorithms
1472     defined below.</p>
1473    
1474     </li>
1475 wakaba 1.3
1476     <li>
1477 wakaba 1.24
1478     <p>Remove the task run in the previous step, if any, from its
1479     <span>task queue</span>.</p>
1480    
1481     </li>
1482 wakaba 1.3
1483     <li>
1484 wakaba 1.24
1485     <p>If there are any more events in the <span>event loop</span>'s
1486     <span title="task queue">task queues</span> or if <var title="">worker global scope</var>'s <a href=#dom-workerglobalscope-closing title=dom-WorkerGlobalScope-closing>closing</a> flag is set
1487     to false, then jump back to the step above labeled <i>event
1488     loop</i>.</p>
1489    
1490     </li>
1491 wakaba 1.3
1492     <li>
1493 wakaba 1.24
1494 wakaba 1.18 <p>Freeze the <span>script group</span>.</p>
1495    
1496     <p class=note>This kills timers, database transactions, etc.</p>
1497 wakaba 1.9
1498 wakaba 1.24 </li>
1499 wakaba 1.3
1500     <li>
1501 wakaba 1.4
1502 wakaba 1.24 <p>For each <code><a href=#worker>Worker</a></code> or <code><a href=#sharedworker>SharedWorker</a></code>
1503     object associated with <var title="">worker global scope</var>,
1504     <span>queue a task</span> to <span>fire a simple event</span>
1505     called <code title=event-close>close</code> at that object.</p>
1506 wakaba 1.3
1507 wakaba 1.24 </li>
1508 wakaba 1.3
1509 wakaba 1.24 </ol><hr><p>When a user agent is to <dfn id=kill-a-worker>kill a worker</dfn> it must
1510     run the following steps in parallel with the worker's main loop (the
1511     "<a href=#run-a-worker>run a worker</a>" processing model defined above):</p>
1512    
1513     <ol><li><p>If the worker's <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object's
1514     <a href=#dom-workerglobalscope-closing title=dom-WorkerGlobalScope-closing>closing</a> flag is
1515     false, <span>queue a task</span> to <span>fire a simple
1516     event</span> called <code title=event-close>close</code> at the
1517     worker's <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object.</li>
1518    
1519     <li><p>Set the worker's <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object's <a href=#dom-workerglobalscope-closing title=dom-WorkerGlobalScope-closing>closing</a> flag to
1520     true.</li>
1521    
1522     <li><p>Wait a user-agent-defined amount of time. If the "<a href=#run-a-worker>run
1523     a worker</a>" processing model defined above immediately starts
1524     running event listeners registered for the <code title=event-close>close</code> event, this time should not be
1525     zero &mdash; the idea is that the <code title=event-close>close</code> event can be used to clean up
1526     when shutting down unexpectedly.</li>
1527    
1528     <li><p>If there are any <span title=concept-task>tasks</span>
1529     queued in the <span>event loop</span>'s <span title="task
1530     queue">task queues</span> other than the <code title=event-close>close</code> event that this algorithm just
1531     added, discard them without processing them.</li>
1532    
1533     <li><p>If the <code title=event-close>close</code> event that
1534     this algorithm just queued hasn't yet been dispatched, then abort
1535     the script currently running in the worker.</li>
1536    
1537     <li><p>Wait a user-agent-defined amount of time.</li>
1538    
1539     <li><p>Abort the script currently running in the worker (if any
1540     script is running, then it will be a handler for the <code title=event-close>close</code> event).</li>
1541    
1542     </ol><p>User agents may invoke the "<a href=#kill-a-worker>kill a worker</a>"
1543     processing model on a worker at any time, e.g. in response to user
1544     requests, in response to CPU quota management, or when a worker
1545     stops being an <a href=#active-needed-worker>active needed worker</a> if the worker
1546     continues executing even after its <a href=#dom-workerglobalscope-closing title=dom-WorkerGlobalScope-closing>closing</a> flag was
1547     set to true.</p>
1548    
1549     <hr><p>When a user agent is to <dfn id=terminate-a-worker>terminate a worker</dfn> it must run
1550     the following steps in parallel with the worker's main loop (the
1551     "<a href=#run-a-worker>run a worker</a>" processing model defined above):</p>
1552    
1553     <ol><li><p>Set the worker's <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object's
1554     <a href=#dom-workerglobalscope-closing title=dom-WorkerGlobalScope-closing>closing</a> flag to
1555     true.</li>
1556    
1557     <li><p>If there are any <span title=concept-task>tasks</span>
1558     queued in the <span>event loop</span>'s <span title="task
1559     queue">task queues</span>, discard them without processing
1560     them.</li>
1561    
1562     <li><p>Abort the script currently running in the worker.</li>
1563    
1564     <li><p>If the worker's <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object is
1565     actually a <code><a href=#dedicatedworkerglobalscope>DedicatedWorkerGlobalScope</a></code> object (i.e. the
1566     worker is a dedicated worker), then empty the <span>port message
1567     queue</span> of the port that the worker's implicit port is
1568     entangled with.</li>
1569    
1570     </ol><h4 id=runtime-script-errors><span class=secno>4.6.1 </span>Runtime script errors</h4>
1571    
1572     <p>Whenever a runtime script error occurs in one of the worker's
1573     scripts, if the error did not occur while handling a previous script
1574     error, the user agent must <span>queue a task</span> to <a href=#fire-an-error-event>fire
1575     an error event</a> at the the <code><a href=#workerglobalscope>WorkerGlobalScope</a></code>
1576     object.</p>
1577    
1578     <p>For shared workers, if the error is still <i title="">not
1579     handled</i> afterwards, or if the error occured while handling a
1580     previous script error, the error should be reported to the user.</p>
1581    
1582     <p>For dedicated workers, if the error is still <i title="">not
1583     handled</i> afterwards, or if the error occured while handling a
1584     previous script error, the user agent must further <span>queue a
1585     task</span> to <a href=#fire-an-error-event>fire an error event</a> at the
1586     <code><a href=#worker>Worker</a></code> object associated with the worker.</p>
1587    
1588     <p>When the user agent is to <dfn id=fire-an-error-event>fire an error event</dfn> at a
1589     <code><a href=#worker>Worker</a></code> object, it must dispatch an event that uses the
1590     <code><a href=#errorevent>ErrorEvent</a></code> interface, with the name <code title=event-error>error</code>, that doesn't bubble and is
1591     cancelable, with its <code title=dom-ErrorEvent-message><a href=#dom-errorevent-message>message</a></code>, <code title=dom-ErrorEvent-filename><a href=#dom-errorevent-filename>filename</a></code>, and <code title=dom-ErrorEvent-lineno><a href=#dom-errorevent-lineno>lineno</a></code> attributes set
1592     appropriately. The default action of this event depends on whether
1593     the <code><a href=#worker>Worker</a></code> object is itself in a worker. If it is, and
1594     that worker is also a dedicated worker, then the user agent must
1595     again <span>queue a task</span> to <a href=#fire-an-error-event>fire an error event</a>
1596     at the <code><a href=#worker>Worker</a></code> object associated with <em>that</em>
1597     worker. Otherwise, then the error should be reported to the
1598     user.</p>
1599    
1600     <hr><pre class=idl>interface <dfn id=errorevent>ErrorEvent</dfn> : Event {
1601     readonly attribute DOMObject <a href=#dom-errorevent-message title=dom-ErrorEvent-message>message</a>;
1602     readonly attribute DOMObject <a href=#dom-errorevent-filename title=dom-ErrorEvent-filename>filename</a>;
1603     readonly attribute unsigned long <a href=#dom-errorevent-lineno title=dom-ErrorEvent-lineno>lineno</a>;
1604     void <a href=#dom-errorevent-initerrorevent title=dom-ErrorEvent-initErrorEvent>initErrorEvent</a>(in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in DOMObject messageArg, in DOMObject filenameArg, in unsigned long linenoArg);
1605     void <a href=#dom-errorevent-initerroreventns title=dom-ErrorEvent-initErrorEventNS>initErrorEventNS</a>(in DOMString namespaceURIArg, in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in DOMObject messageArg, in DOMObject filenameArg, in unsigned long linenoArg);
1606     };</pre>
1607 wakaba 1.3
1608 wakaba 1.24 <p>The <dfn id=dom-errorevent-initerrorevent title=dom-ErrorEvent-initErrorEvent><code>initErrorEvent()</code></dfn>
1609     and <dfn id=dom-errorevent-initerroreventns title=dom-ErrorEvent-initErrorEventNS><code>initErrorEventNS()</code></dfn>
1610     methods must initialize the event in a manner analogous to the
1611     similarly-named methods in the DOM3 Events interfaces. <a href=#refsDOM3EVENTS>[DOM3EVENTS]</a></p>
1612 wakaba 1.3
1613 wakaba 1.24 <p>The <dfn id=dom-errorevent-message title=dom-ErrorEvent-message><code>message</code></dfn>
1614     attribute represents the error message.</p>
1615 wakaba 1.3
1616 wakaba 1.24 <p>The <dfn id=dom-errorevent-filename title=dom-ErrorEvent-filename><code>filename</code></dfn>
1617     attribute represents the <span>absolute URL</span> of the script in
1618     which the error originally occured.</p>
1619 wakaba 1.4
1620 wakaba 1.24 <p>The <dfn id=dom-errorevent-lineno title=dom-ErrorEvent-lineno><code>lineno</code></dfn>
1621     attribute represents the line number where the error occured in the
1622     script.</p>
1623 wakaba 1.4
1624    
1625 wakaba 1.19
1626 wakaba 1.24 <h3 id=creating-workers><span class=secno>4.7 </span>Creating workers</h3>
1627 wakaba 1.20
1628 wakaba 1.24 <h4 id=the-abstractworker-abstract-interface><span class=secno>4.7.1 </span>The <code><a href=#abstractworker>AbstractWorker</a></code> abstract interface</h4>
1629 wakaba 1.12
1630 wakaba 1.22 <pre class=idl>interface <dfn id=abstractworker>AbstractWorker</dfn> {
1631 wakaba 1.24 attribute <span>EventListener</span> <a href=#handler-abstractworker-onerror title=handler-AbstractWorker-onerror>onerror</a>;
1632     attribute <span>EventListener</span> <a href=#handler-abstractworker-onclose title=handler-AbstractWorker-onclose>onclose</a>;
1633 wakaba 1.12 };</pre>
1634    
1635 wakaba 1.24 <p>Objects implementing the <code><a href=#abstractworker>AbstractWorker</a></code> interface
1636     must also implement the <code>EventTarget</code> interface.</p>
1637    
1638     <p>The following are the <span>event handler DOM attributes</span>
1639     that must be supported by objects implementing the
1640     <code><a href=#abstractworker>AbstractWorker</a></code> interface:</p>
1641    
1642     <dl><dt><dfn id=handler-abstractworker-onerror title=handler-AbstractWorker-onerror><code>onerror</code></dfn></dt>
1643    
1644     <dd><p>Must be invoked whenever an <code title=event-error>error</code> event is targeted at or bubbles
1645     through the <code><a href=#abstractworker>AbstractWorker</a></code> object.</dd>
1646    
1647     <dt><dfn id=handler-abstractworker-onclose title=handler-AbstractWorker-onclose><code>onclose</code></dfn></dt>
1648 wakaba 1.12
1649 wakaba 1.24 <dd><p>Must be invoked whenever an <code title=event-close>close</code> event is targeted at or bubbles
1650     through the <code><a href=#abstractworker>AbstractWorker</a></code> object.</dd>
1651 wakaba 1.12
1652 wakaba 1.24 </dl><h4 id=dedicated-workers-and-the-worker-interface><span class=secno>4.7.2 </span>Dedicated workers and the <code><a href=#worker>Worker</a></code> interface</h4>
1653 wakaba 1.12
1654 wakaba 1.24 <pre class=idl>[<a href=#dom-worker title=dom-Worker>Constructor</a>(in DOMString scriptURL)]
1655     interface <dfn id=worker>Worker</dfn> : <a href=#abstractworker>AbstractWorker</a> {
1656     void <a href=#dom-worker-terminate title=dom-Worker-terminate>terminate</a>();
1657 wakaba 1.12
1658 wakaba 1.24 void <a href=#dom-worker-postmessage title=dom-Worker-postMessage>postMessage</a>(in any message, [Optional] in <span>MessagePortArray</span> ports);<!--
1659 wakaba 1.22 <span>MessagePort</span> <span title="dom-Worker-startConversation">startConversation</span>(in any message);-->
1660 wakaba 1.24 attribute <span>EventListener</span> <a href=#handler-worker-onmessage title=handler-Worker-onmessage>onmessage</a>;
1661 wakaba 1.3 };</pre>
1662    
1663 wakaba 1.24 <p>The <dfn id=dom-worker-terminate title=dom-Worker-terminate><code>terminate()</code></dfn> method,
1664     when invoked, must cause the "<a href=#terminate-a-worker>terminate a worker</a>"
1665     algorithm to be run on the worker with with the object is
1666     associated.</p>
1667    
1668     <p><code><a href=#worker>Worker</a></code> objects act as if they had an implicit
1669     <code>MessagePort</code> associated with them. This port is part of
1670     a channel that is set up when the worker is created, but it is not
1671     exposed. This object must never be garbage collected before the
1672     <code><a href=#worker>Worker</a></code> object.</p>
1673 wakaba 1.12
1674 wakaba 1.24 <p>All messages received by that port must immediately be
1675     retargetted at the <code><a href=#worker>Worker</a></code> object.</p>
1676 wakaba 1.12
1677 wakaba 1.24 <p>The <dfn id=dom-worker-postmessage title=dom-Worker-postMessage><code>postMessage()</code></dfn><!--
1678 wakaba 1.14 and <dfn
1679     title="dom-Worker-startConversation"><code>startConversation()</code></dfn>-->
1680 wakaba 1.24 method<!--s (startConversation)--> on <code><a href=#worker>Worker</a></code> objects
1681     must act as if, when invoked, it<!--/they (startConversation)-->
1682     immediately invoked the method of the same name on the port, with
1683     the same arguments, and returned the same return value.</p>
1684    
1685     <p>The following are the <span>event handler DOM attributes</span>
1686     that must be supported by objects implementing the
1687     <code><a href=#worker>Worker</a></code> interface:</p>
1688    
1689     <dl><dt><dfn id=handler-worker-onmessage title=handler-Worker-onmessage><code>onmessage</code></dfn></dt>
1690 wakaba 1.12
1691 wakaba 1.24 <dd><p>Must be invoked whenever a <code title=event-Worker-message>message</code> event is targeted
1692     at or bubbles through the <code><a href=#worker>Worker</a></code> object.</dd>
1693    
1694     </dl><hr><p>When the <dfn id=dom-worker title=dom-Worker><code>Worker(<var title="">scriptURL</var>)</code></dfn> constructor is invoked, the
1695     user agent must run the following steps:</p>
1696    
1697     <ol><li><p><span title="resolve a url">Resolve</span> the <var title="">scriptURL</var> argument.</li>
1698    
1699     <li><p>If this fails, throw a <code>SYNTAX_ERR</code>
1700     exception.</li>
1701    
1702     <li><p>If the <span>origin</span> of the resulting <span>absolute
1703     URL</span> is not the <span title="same origin">same</span> as the
1704     origin of the script that invoked the constructor, then throw a
1705     <span>security exception</span>.</li>
1706    
1707     <li><p><span>Create a new <code><a href=#dedicatedworkerglobalscope>DedicatedWorkerGlobalScope</a></code>
1708     object</span>. Let <var title="">worker global scope</var> be this
1709     new object.</li>
1710 wakaba 1.4
1711 wakaba 1.24 <li><p>Create a new <code><a href=#worker>Worker</a></code> object, associated with
1712     <var title="">worker global scope</var>. Let <var title="">worker</var> be this new object.</li>
1713 wakaba 1.5
1714 wakaba 1.24 <li><p><span>Create a <code>MessagePort</code> object</span> owned
1715     by the <span>script execution context</span> of the script that
1716     invoked the method. Let this be the <var title="">outside
1717     port</var>.</li>
1718 wakaba 1.5
1719 wakaba 1.24 <li><p>Associate the <var title="">outside port</var> with <var title="">worker</var>.</li>
1720 wakaba 1.5
1721 wakaba 1.24 <li><p><span>Create a <code>MessagePort</code> object</span> owned
1722     by <var title="">worker global scope</var>. Let <var title="">inside port</var> be this new object.</li>
1723 wakaba 1.12
1724 wakaba 1.24 <li><p>Associate <var title="">inside port</var> with <var title="">worker global scope</var>.</li>
1725 wakaba 1.5
1726 wakaba 1.24 <li><p><span>Entangle</span> <var title="">outside port</var> and
1727     <var title="">inside port</var>.</li>
1728 wakaba 1.12
1729 wakaba 1.24 <li><p>Return <var title="">worker</var>, and run the following
1730     steps asynchronously.</li>
1731 wakaba 1.12
1732 wakaba 1.24 <li><p>Open <var title="">inside port</var>'s <span>port message
1733     queue</span>.</li>
1734 wakaba 1.12
1735 wakaba 1.24 <li><p>Open <var title="">outside port</var>'s <span>port message
1736     queue</span>.</li>
1737 wakaba 1.12
1738     <li>
1739    
1740 wakaba 1.24 <p><a href=#run-a-worker>Run a worker</a> for the resulting <span>absolute
1741     URL</span>, with the <span>script browsing context</span> of the
1742     script that invoked the method as the <var title="">owner browsing
1743     context</var>, and with <var title="">worker global scope</var> as
1744     the global scope.</p>
1745 wakaba 1.12
1746 wakaba 1.24 </li>
1747 wakaba 1.12
1748 wakaba 1.24 </ol><h4 id=shared-workers-and-the-sharedworker-interface><span class=secno>4.7.3 </span>Shared workers and the <code><a href=#sharedworker>SharedWorker</a></code> interface</h4>
1749 wakaba 1.13
1750 wakaba 1.24 <pre class=idl>[<a href=#dom-sharedworker title=dom-SharedWorker>Constructor</a>(in DOMString scriptURL, in DOMString name)]
1751     interface <dfn id=sharedworker>SharedWorker</dfn> : <a href=#abstractworker>AbstractWorker</a> {
1752     readonly attribute <span>MessagePort</span> <a href=#dom-sharedworker-port title=dom-SharedWorker-port>port</a>;
1753 wakaba 1.12 };</pre>
1754    
1755 wakaba 1.24 <p>The <dfn id=dom-sharedworker-port title=dom-SharedWorker-port><code>port</code></dfn>
1756     attribute must return the value it was assigned by the object's
1757     constructor. It represents the <code>MessagePort</code> for
1758     communicating with the shared worker.</p>
1759    
1760     <p>When the <dfn id=dom-sharedworker title=dom-SharedWorker><code>SharedWorker(<var title="">scriptURL</var>, <var title="">name</var>)</code></dfn>
1761     constructor is invoked, the user agent must run the following
1762     steps:</p>
1763    
1764     <ol><li><p><span title="resolve a url">Resolve</span> the <var title="">scriptURL</var> argument.</li>
1765    
1766     <li><p>If this fails, throw a <code>SYNTAX_ERR</code>
1767     exception.</li>
1768    
1769     <li><p>If the <span>origin</span> of the resulting <span>absolute
1770     URL</span> is not the <span title="same origin">same</span> as the
1771     origin of the script that invoked the constructor, then throw a
1772     <span>security exception</span>.</li>
1773 wakaba 1.4
1774 wakaba 1.5 <li>
1775    
1776 wakaba 1.24 <p>Execute the following substeps atomically:</p>
1777 wakaba 1.5
1778 wakaba 1.24 <ol><li><p>Create a new <code><a href=#sharedworker>SharedWorker</a></code> object, which will
1779     shortly be associated with a <code><a href=#sharedworkerglobalscope>SharedWorkerGlobalScope</a></code>
1780     object. Let this <code><a href=#sharedworker>SharedWorker</a></code> object be <var title="">worker</var>.</li>
1781    
1782     <li><p><span>Create a <code>MessagePort</code> object</span> owned
1783     by the <span>script execution context</span> of the script that
1784     invoked the method. Let this be the <var title="">outside
1785     port</var>.</li>
1786 wakaba 1.5
1787 wakaba 1.24 <li><p>Assign <var title="">outside port</var> to the <code title=dom-SharedWorker-port><a href=#dom-sharedworker-port>port</a></code> attribute of <var title="">worker</var>.</li>
1788 wakaba 1.5
1789     <li>
1790    
1791 wakaba 1.24 <p>If there exists a <code><a href=#sharedworkerglobalscope>SharedWorkerGlobalScope</a></code> object
1792     whose <a href=#dom-workerglobalscope-closing title=dom-WorkerGlobalScope-closing>closing</a>
1793     flag is false, whose <code title=dom-WorkerGlobalScope-name>name</code> attribute is
1794     exactly equal to the <var title="">name</var> argument, and
1795     whose <code title=dom-WorkerGlobalScope-location><a href=#dom-workerglobalscope-location>location</a></code> attribute
1796     represents an <span>absolute URL</span> that has the <span>same
1797     origin</span> as the resulting <span>absolute URL</span>, then
1798     run these substeps:</p>
1799    
1800     <ol><li><p>Let <var title="">worker global scope</var> be that
1801     <code><a href=#sharedworkerglobalscope>SharedWorkerGlobalScope</a></code> object.</li>
1802    
1803     <li><p>If <var title="">worker global scope</var>'s <code title=dom-WorkerGlobalScope-location><a href=#dom-workerglobalscope-location>location</a></code>
1804     attribute represents an <span>absolute URL</span> that is not
1805     exactly equal to the resulting <span>absolute URL</span>, then
1806     throw a <code>URL_MISMATCH_ERR</code> exception and abort all
1807     these steps. <span class=XXX>code 21</span></li>
1808    
1809     <li><p>Associate <var title="">worker</var> with <var title="">worker global scope</var>.</li>
1810    
1811     <li><p><span>Create a <code>MessagePort</code> object</span>
1812     owned by <var title="">worker global scope</var>. Let this
1813     be the <var title="">inside port</var>.</li>
1814    
1815     <li><p><span>Entangle</span> <var title="">outside port</var>
1816     and <var title="">inside port</var>.</li>
1817    
1818     <li><p>Return <var title="">worker</var> and perform the next
1819     step asynchronously.</li>
1820    
1821     <li><p>Create an event that uses the <code>MessageEvent</code>
1822     interface, with the name <code title=event-connect>connect</code>, which does not bubble, is
1823     cancelable, has no default action, has a <code title=dom-MessageEvent-data>data</code> attribute whose value
1824     is the empty string and has a <code title=dom-MessageEvent-ports>ports</code>
1825     attribute whose value is an array containing only the newly
1826     created port, and <span>queue a task</span> to dispatch the
1827     event at <var title="">worker global scope</var>.</li>
1828    
1829     <li><p>Abort all these steps.</li>
1830    
1831     </ol></li>
1832    
1833     <li><p><span>Create a new <code><a href=#sharedworkerglobalscope>SharedWorkerGlobalScope</a></code>
1834     object</span>. Let <var title="">worker global scope</var> be
1835     this new object.</li>
1836 wakaba 1.5
1837 wakaba 1.24 <li><p>Associate <var title="">worker</var> with <var title="">worker global scope</var>.</li>
1838 wakaba 1.9
1839 wakaba 1.24 <li><p>Set the <code title=dom-SharedWorkerGlobalScope-name><a href=#dom-sharedworkerglobalscope-name>name</a></code> attribute of
1840     <var title="">worker global scope</var> to <var title="">name</var>.</li>
1841 wakaba 1.5
1842 wakaba 1.24 <li><p><span>Create a <code>MessagePort</code> object</span>
1843     owned by <var title="">worker global scope</var>. Let <var title="">inside port</var> be this new object.</li>
1844 wakaba 1.5
1845 wakaba 1.24 <li><p><span>Entangle</span> <var title="">outside port</var> and
1846     <var title="">inside port</var>.</li>
1847 wakaba 1.4
1848 wakaba 1.24 </ol></li>
1849 wakaba 1.4
1850 wakaba 1.24 <li><p>Return <var title="">worker</var> and perform the next step
1851     asynchronously.</li>
1852 wakaba 1.4
1853 wakaba 1.24 <li><p>Create an event that uses the <code>MessageEvent</code>
1854     interface, with the name <code title=event-connect>connect</code>, which does not bubble, is
1855     cancelable, has no default action, has a <code title=dom-MessageEvent-data>data</code> attribute whose value is
1856     the empty string and has a <code title=dom-MessageEvent-ports>ports</code> attribute
1857     whose value is an array containing only the newly created port, and
1858     <span>queue a task</span> to dispatch the event at <var title="">worker global scope</var>.</li>
1859 wakaba 1.5
1860     <li>
1861    
1862 wakaba 1.24 <p><a href=#run-a-worker>Run a worker</a> for the resulting <span>absolute
1863     URL</span>, with the <span>script browsing context</span> of the
1864     script that invoked the method as the <var title="">owner browsing
1865     context</var>, and with <var title="">worker global scope</var> as
1866     the global scope.</p>
1867    
1868     </li>
1869 wakaba 1.8
1870 wakaba 1.24 </ol><h2 id=apis-available-to-workers><span class=secno>5 </span>APIs available to workers</h2>
1871 wakaba 1.3
1872 wakaba 1.22 <!-- the XXX below is for collapsing this interface onto WorkerGlobalScope so it looks like just one interface - the inheritance is a spec fiction only -->
1873 wakaba 1.24 <pre class=idl>[NoInterfaceObject, ImplementedOn=WorkerGlobalScope, XXX] interface <dfn id=workerutils>WorkerUtils</dfn> {
1874     void <a href=#dom-workerglobalscope-importscripts title=dom-WorkerGlobalScope-importScripts>importScripts</a>([Variadic] in DOMString urls);
1875     readonly attribute <span>Storage</span> <a href=#dom-localstorage title=dom-localStorage>localStorage</a>;
1876     readonly attribute <a href=#navigator>Navigator</a> <a href=#dom-navigator title=dom-navigator>navigator</a>;
1877     <span>Database</span> <a href=#dom-opendatabase title=dom-opendatabase>openDatabase</a>(in DOMString name, in DOMString version, in DOMString displayName, in unsigned long estimatedSize);<!--
1878 wakaba 1.22 void <span title="dom-showNotification">showNotification</span>(in DOMString title, in DOMString subtitle, in DOMString description, [Optional] in VoidCallback onclick); XXX-NOTIFY -->
1879 wakaba 1.7 };</pre>
1880 wakaba 1.6
1881 wakaba 1.24 <p>Objects that implement the <code><a href=#workerglobalscope>WorkerGlobalScope</a></code>
1882     interface must also implement the <code><a href=#workerutils>WorkerUtils</a></code>
1883     interface.</p>
1884    
1885     <p>Objects that implement the <code><a href=#workerutils>WorkerUtils</a></code> interface
1886     must also implement the <code>WindowTimers</code> interface. (This
1887     interface provides the <code title="">setTimeout()</code> method and
1888     its friends.)</p>
1889    
1890     <p class=XXX>Need to define a sync database API.</p>
1891 wakaba 1.6
1892     <!-- XXX ApplicationCache -->
1893 wakaba 1.24
1894 wakaba 1.6 <!-- XXX a way to set cookies on the URL for the script -->
1895 wakaba 1.24
1896 wakaba 1.6 <!-- XXX debugging: void log(in DOMString s); // log to console -->
1897 wakaba 1.24
1898 wakaba 1.6 <!-- XXX debugging: onerror -->
1899    
1900 wakaba 1.24 <hr><p>The DOM APIs (<code>Node</code> objects, <code>Document</code>
1901     objects, etc) are not available to workers in this version of this
1902     specification.</p>
1903    
1904 wakaba 1.6
1905 wakaba 1.24 <h3 id=importing-scripts-and-libraries><span class=secno>5.1 </span>Importing scripts and libraries</h3>
1906 wakaba 1.6
1907 wakaba 1.24 <p>When a script invokes the <dfn id=dom-workerglobalscope-importscripts title=dom-WorkerGlobalScope-importScripts><code>importScripts(<var title="">urls</var>)</code></dfn> method on a
1908     <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object, the user agent must run the
1909     following steps:</p>
1910 wakaba 1.7
1911 wakaba 1.24 <ol><li><p>If there are no arguments, return without doing
1912     anything. Abort these steps.</li>
1913 wakaba 1.7
1914 wakaba 1.24 <li><p><span title="resolve a url">Resolve</span> each
1915     argument.</li>
1916 wakaba 1.9
1917 wakaba 1.24 <li><p>If any fail, throw a <code>SYNTAX_ERR</code>
1918     exception.</li>
1919 wakaba 1.7
1920 wakaba 1.24 <!--
1921 wakaba 1.17 <li><p>If any of the resulting <span title="absolute URL">absolute
1922     URLs</span> have an <span>origin</span> that is not the <span
1923     title="same origin">same</span> as the origin of the script that
1924     invoked the method, then throw a <span>security
1925     exception</span>.</p></li>
1926     -->
1927 wakaba 1.7
1928     <li>
1929 wakaba 1.24
1930 wakaba 1.9 <p>Attempt to <span>fetch</span> each resource identified by the
1931 wakaba 1.24 resulting <span title="absolute URLs">absolute URL</span>.</p>
1932    
1933     </li>
1934 wakaba 1.7
1935     <li>
1936    
1937 wakaba 1.24 <p>For each argument in turn, in the order given, starting with
1938     the first one, run these substeps:</p>
1939    
1940     <ol><li>
1941    
1942     <p>Wait for the fetching attempt for the corresponding resource
1943     to complete.</p>
1944    
1945     <p>If the fetching attempt failed, throw a
1946     <code>NETWORK_ERR</code> exception and abort all these
1947     steps.</p>
1948    
1949     <p>If the attempt succeeds, then <a href=#decode-a-script-resource title="decode a script
1950     resource">decode the script resource</a> to obtain its <var title="">source</var>.</p>
1951    
1952     <p>Let <var title="">language</var> be JavaScript.</p>
1953 wakaba 1.7
1954 wakaba 1.24 <p class=note>As with the worker's script, the script here is
1955     always assumed to be JavaScript, regardless of the MIME
1956     type.</p> <!-- XXX -->
1957 wakaba 1.7
1958 wakaba 1.24 </li>
1959 wakaba 1.7
1960 wakaba 1.9 <li>
1961 wakaba 1.24
1962     <p><span>Create a script</span>, using <var title="">source</var> as the script source and <var title="">language</var> as the scripting language, using the
1963     same global object, browsing context, character encoding, base
1964     URL, and script group as the <span title=concept-script>script</span> that was created by the
1965     worker's <a href=#run-a-worker>run a worker</a> algorithm.</p>
1966    
1967     <p>Let the newly created <span title=concept-script>script</span> run until it either
1968     returns, fails to parse, fails to catch an exception, or gets
1969     prematurely aborted by the "<a href=#kill-a-worker>kill a worker</a>" or
1970     "<a href=#terminate-a-worker>terminate a worker</a>" algorithms defined above.</p>
1971 wakaba 1.14
1972     <p>If it failed to parse, then throw a
1973 wakaba 1.24 <code>SyntaxError</code><!-- XXX ref? --> exception and abort
1974     all these steps.</p>
1975    
1976     <p>If an exception was raised or if the script was prematurely
1977     aborted, then abort all these steps, letting the exception or
1978     aborting continue to be processed by the script that called the
1979     <code title=dom-WorkerGlobalScope-importScripts><a href=#dom-workerglobalscope-importscripts>importScripts()</a></code>
1980     method.</p>
1981    
1982     <p>If the "<a href=#kill-a-worker>kill a worker</a>" or "<a href=#terminate-a-worker>terminate a
1983     worker</a>" algorithms abort the script then abort all these
1984     steps.</p>
1985    
1986     </li>
1987    
1988     </ol></li>
1989 wakaba 1.9
1990 wakaba 1.24 </ol><h3 id=the-navigator-object><span class=secno>5.2 </span>The <code><a href=#navigator>Navigator</a></code> object</h3>
1991 wakaba 1.14
1992 wakaba 1.24 <p>The <dfn id=dom-navigator title=dom-navigator><code>navigator</code></dfn>
1993     attribute of the <code><a href=#workerutils>WorkerUtils</a></code> interface must return an
1994     instance of the <code><a href=#navigator>Navigator</a></code> interface, which represents
1995     the identity and state of the user agent (the client):</p>
1996    
1997     <pre class=idl>interface <dfn id=navigator>Navigator</dfn> {
1998 wakaba 1.14 // objects implementing this interface also implement the interfaces listed below
1999     };</pre>
2000    
2001 wakaba 1.24 <p>Objects implementing the <code><a href=#navigator>Navigator</a></code> interface must
2002     also implement the <span>NavigatorID</span> and
2003     <span>NavigatorOnLine</span> interfaces specified in the HTML5
2004     specification. <a href=#refsHTML5>[HTML5]</a></p>
2005    
2006     <p class=note>The <code><a href=#navigator>Navigator</a></code> interface defined in this
2007     specification is different than the one defined in the HTML5
2008     specification.</p>
2009    
2010    
2011     <h3 id=apis-defined-in-other-specifications><span class=secno>5.3 </span>APIs defined in other specifications</h3>
2012 wakaba 1.7
2013 wakaba 1.24 <p>The <dfn id=dom-localstorage title=dom-localStorage><code>localStorage</code></dfn>,
2014     <dfn id=dom-opendatabase title=dom-opendatabase><code>openDatabase()</code></dfn> must
2015     act as defined for the APIs with the same names on the
2016     <code>Window</code> object in the HTML5 specification, with the
2017     exception that where the API would use the <span>origin</span> of
2018     the <span>active document</span> of the <span>browsing
2019     context</span> of the <code>Window</code> object on which the method
2020     was supposedly invoked, it must instead use the <span>origin</span>
2021     of the script that invoked the method. <a href=#refsHTML5>[HTML5]</a></p>
2022    
2023     <p>The <dfn id=dom-shownotification title=dom-showNotification><code>showNotification()</code></dfn>
2024     methods must act as defined for the APIs with the same names on the
2025     <code>Window</code> object in the HTML5 specification. <a href=#refsHTML5>[HTML5]</a></p>
2026    
2027    
2028     <h3 id=interface-objects-and-constructors><span class=secno>5.4 </span>Interface objects and constructors</h3>
2029    
2030     <p>There must be no interface objects and constructors available in
2031     the global scope of scripts whose <span>script execution
2032     context</span> is a <code><a href=#workerglobalscope>WorkerGlobalScope</a></code> object except for
2033     the following:</p>
2034    
2035     <ul><li><p><code>XMLHttpRequest</code> and all interface objects and
2036     constructors defined by the XMLHttpRequest specifications, except
2037     that the <span>document response entity body</span> must always be
2038     null. <a href=#refsXHR>[XHR]</a></li>
2039 wakaba 1.7
2040 wakaba 1.24 <li><p>The <code>WebSocket</code> interface object and
2041     constructor.</li>
2042 wakaba 1.7
2043 wakaba 1.24 <li><p>The <code>MessageChannel</code> interface object and
2044     constructor.</li>
2045 wakaba 1.14
2046 wakaba 1.24 <li><p>The <code title=dom-Worker><a href=#dom-worker>Worker()</a></code> and <code title=dom-SharedWorker><a href=#dom-sharedworker>SharedWorker(<var title="">url</var>)</a></code> constructors.</li>
2047 wakaba 1.8
2048 wakaba 1.24 </ul><h3 id=worker-locations><span class=secno>5.5 </span>Worker locations</h3>
2049 wakaba 1.8
2050 wakaba 1.22 <pre class=idl>interface <dfn id=workerlocation>WorkerLocation</dfn> {
2051 wakaba 1.24 readonly attribute DOMString <a href=#dom-workerlocation-href title=dom-WorkerLocation-href>href</a>;
2052     readonly attribute DOMString <a href=#dom-workerlocation-protocol title=dom-WorkerLocation-protocol>protocol</a>;
2053     readonly attribute DOMString <a href=#dom-workerlocation-host title=dom-WorkerLocation-host>host</a>;
2054     readonly attribute DOMString <a href=#dom-workerlocation-hostname title=dom-WorkerLocation-hostname>hostname</a>;
2055     readonly attribute DOMString <a href=#dom-workerlocation-port title=dom-WorkerLocation-port>port</a>;
2056     readonly attribute DOMString <a href=#dom-workerlocation-pathname title=dom-WorkerLocation-pathname>pathname</a>;
2057     readonly attribute DOMString <a href=#dom-workerlocation-search title=dom-WorkerLocation-search>search</a>;
2058     readonly attribute DOMString <a href=#dom-workerlocation-hash title=dom-WorkerLocation-hash>hash</a>;
2059 wakaba 1.8 };</pre>
2060    
2061 wakaba 1.24 <p>A <code><a href=#workerlocation>WorkerLocation</a></code> object represents an <span>absolute
2062     URL</span> set at its creation.</p>
2063    
2064     <p>The <dfn id=dom-workerlocation-href title=dom-WorkerLocation-href><code>href</code></dfn>
2065     attribute must return the <span>absolute URL</span> that the object
2066     represents.</p>
2067    
2068     <p>The <code><a href=#workerlocation>WorkerLocation</a></code> interface also has the complement
2069     of <span>URL decomposition attributes</span>, <dfn id=dom-workerlocation-protocol title=dom-WorkerLocation-protocol><code>protocol</code></dfn>,
2070     <dfn id=dom-workerlocation-host title=dom-WorkerLocation-host><code>host</code></dfn>, <dfn id=dom-workerlocation-port title=dom-WorkerLocation-port><code>port</code></dfn>, <dfn id=dom-workerlocation-hostname title=dom-WorkerLocation-hostname><code>hostname</code></dfn>,
2071     <dfn id=dom-workerlocation-pathname title=dom-WorkerLocation-pathname><code>pathname</code></dfn>,
2072     <dfn id=dom-workerlocation-search title=dom-WorkerLocation-search><code>search</code></dfn>,
2073     and <dfn id=dom-workerlocation-hash title=dom-WorkerLocation-hash><code>hash</code></dfn>. These must
2074     follow the rules given for URL decomposition attributes, with the
2075     <span title=concept-uda-input>input</span> being the
2076     <span>absolute URL</span> that the object represents (same as the
2077     <code title=dom-WorkerLocation-href><a href=#dom-workerlocation-href>href</a></code> attribute), and
2078     the <span title=concept-uda-setter>common setter action</span>
2079     being a no-op, since the attributes are defined to be readonly. <a href=#refsHTML5>[HTML5]</a></p>
2080    
2081    
2082 wakaba 1.8
2083 wakaba 1.7
2084 wakaba 1.1 <h2 class=no-num id=references>References</h2>
2085    
2086     <p class=big-issue>This section will be written in a future
2087 wakaba 1.24 draft.<!--XXX--></p>
2088    
2089    
2090     <h2 class=no-num id=acknowledgements>Acknowledgements</h2> <!-- ACKS -->
2091    
2092     <p>Thanks to
2093    
2094     Aaron Boodman,
2095     &#1040;&#1083;&#1077;&#1082;&#1089;&#1077;&#1081; &#1055;&#1088;&#1086;&#1089;&#1082;&#1091;&#1088;&#1103;&#1082;&#1086;&#1074; (Alexey Proskuryakov),
2096     Anne van Kesteren,
2097     Ben Turner,
2098     Dmitry Titov,
2099     Jonas Sicking,
2100     Justin James,
2101     Kevin Hakanson,
2102     Maciej Stachowiak,
2103     Michael Nordman,
2104     Mike Smith,
2105    
2106     and
2107    
2108     Philip Taylor
2109 wakaba 1.1
2110 wakaba 1.24 for their useful and substantial comments.</p>
2111 wakaba 1.1
2112 wakaba 1.24 <p>Huge thanks to the whole Gears team, who pioneered this
2113     technology and whose experience has been a huge influence on this
2114     specification.</p>
2115 wakaba 1.3
2116 wakaba 1.24

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24