/[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.127 - (hide annotations) (download) (as text)
Mon Aug 10 06:17:37 2009 UTC (16 years, 7 months ago) by wakaba
Branch: MAIN
Changes since 1.126: +193 -66 lines
File MIME type: text/html
make

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

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24