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