Annotation of html5/workers/Overview.html, revision 1.107

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

Webmaster