/[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.109 - (hide annotations) (download) (as text)
Fri Jul 17 06:19:28 2009 UTC (16 years, 8 months ago) by wakaba
Branch: MAIN
Changes since 1.108: +5 -5 lines
File MIME type: text/html
make

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

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24