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