/[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.29 - (hide annotations) (download) (as text)
Fri Mar 27 06:18:31 2009 UTC (17 years ago) by wakaba
Branch: MAIN
Changes since 1.28: +12 -13 lines
File MIME type: text/html
make

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

admin@suikawiki.org
ViewVC Help
Powered by ViewVC 1.1.24