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

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

Webmaster