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