forked from w3c/ServiceWorker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.bs
3639 lines (2910 loc) · 245 KB
/
index.bs
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
<pre class='metadata'>
Title: Service Workers Nightly
Status: ED
ED: https://w3c.github.io/ServiceWorker/
TR: https://www.w3.org/TR/service-workers/
Shortname: service-workers
Level:
Editor: Alex Russell, Google, [email protected]
Editor: Jungkee Song, Samsung Electronics, [email protected]
Editor: Jake Archibald, Google, [email protected]
Editor: Marijn Kruisselbrink, Google, [email protected]
Repository: w3c/ServiceWorker
Group: webplatform
Status Text: This is a living document addressing new features including foreign fetch, header-based installation, navigation preload, etc. Readers need to be aware that this specification may include unstable features. <a href="https://w3c.github.io/ServiceWorker/v1/">Service Workers 1</a> is a version that is advancing toward a W3C Recommendation.
Abstract: This specification describes a method that enables applications to take advantage of persistent background processing, including hooks to enable bootstrapping of web applications while offline.
Abstract:
Abstract: The core of this system is an event-driven <a>Web Worker</a>, which responds to events dispatched from documents and other sources. A system for managing installation, versions, and upgrades is provided.
Abstract:
Abstract: The service worker is a generic entry point for event-driven background processing in the Web Platform that is <a href="#extensibility">extensible by other specifications</a>.
Markup Shorthands: css no, markdown yes
</pre>
<pre class="link-defaults">
spec: html;
type: dfn; text: task queues; for: /
type: element; text: link
spec: dom;
type: interface; text: Document
spec: fetch;
type: dfn
for: /; text: fetch
text: empty
type: interface
text: ReadableStream
spec: infra;
type: dfn;
for: set; text: append
for: list; text: append
</pre>
<pre class="anchors">
spec: push; urlPrefix: https://w3c.github.io/push-api/
type: event
text: push; url: h-the-push-event
spec: ecma-262; urlPrefix: http://tc39.github.io/ecma262/
type: dfn
text: Assert; url: sec-algorithm-conventions
text: [[Call]]; url: sec-ecmascript-function-objects-call-thisargument-argumentslist
text: promise; url: sec-promise-objects
text: DetachArrayBuffer; url: sec-detacharraybuffer
url: sec-list-and-record-specification-type
text: List
text: Record
text: map objects; url: sec-map-objects
text: InitializeHostDefinedRealm; url: sec-initializehostdefinedrealm
text: execution context; url: sec-execution-contexts
spec: page-visibility; urlPrefix: https://www.w3.org/TR/page-visibility/
type: enum; text: VisibilityState; url: VisibilityState
type: attribute; text: visibilityState; for: Document; url: dom-document-visibilitystate
spec: html; urlPrefix: https://html.spec.whatwg.org/multipage/
type: attribute
urlPrefix: comms.html
text: origin; for: MessageEvent; url: dom-messageevent-origin
text: source; for: MessageEvent; url: dom-messageevent-source
text: ports; for: MessageEvent; url: dom-messageevent-ports
text: data; for: MessageEvent; url: dom-messageevent-data
type: dfn
urlPrefix: browsers.html
text: ancestor origins list; for: Location; url: concept-location-ancestor-origins-list
urlPrefix: syntax.html
text: delay the load event; for: document; url: delay-the-load-event
spec: fetch; urlPrefix: https://fetch.spec.whatwg.org/
type: dfn
text: response; for: Response; url: concept-response-response
text: request; for: Request; url: concept-request-request
text: HTTP fetch; for: /; url: concept-http-fetch
spec: rfc5988; urlPrefix: https://tools.ietf.org/html/rfc5988
type: dfn
text: context IRI; url: section-5.2
text: target attribute; url: section-5.4
text: target IRI; url: section-5.1
spec: rfc7230; urlPrefix: https://tools.ietf.org/html/rfc7230
type: dfn
text: field-value; for: http; url: section-3.2
spec: rfc7231; urlPrefix: https://tools.ietf.org/html/rfc7231
type: dfn
text: Vary; url: section-7.1.4
spec: webappsec-referrer-policy; urlPrefix: https://w3c.github.io/webappsec-referrer-policy/
type: dfn
text: Parse a referrer policy from a Referrer-Policy header; url: parse-referrer-policy-from-header
</pre>
<pre class="biblio">
{
"unsanctioned-tracking": {
"href": "https://www.w3.org/2001/tag/doc/unsanctioned-tracking/",
"title": "Unsanctioned Web Tracking",
"date": "17 July 2015",
"status": "Finding of the W3C TAG",
"publisher": "W3C TAG"
}
}
</pre>
<section>
<h2 id="motivations">Motivations</h2>
*This section is non-normative.*
Web Applications traditionally assume that the network is reachable. This assumption pervades the platform. HTML documents are loaded over HTTP and traditionally fetch all of their sub-resources via subsequent HTTP requests. This places web content at a disadvantage versus other technology stacks.
The [=/service worker=] is designed first to redress this balance by providing a Web Worker context, which can be started by a runtime when navigations are about to occur. This event-driven worker is registered against an origin and a path (or pattern), meaning it can be consulted when navigations occur to that location. Events that correspond to network requests are dispatched to the worker and the responses generated by the worker may override default network stack behavior. This puts the [=/service worker=], conceptually, between the network and a document renderer, allowing the [=/service worker=] to provide content for documents, even while offline.
Web developers familiar with previous attempts to solve the offline problem have reported a deficit of flexibility in those solutions. As a result, the [=/service worker=] is highly procedural, providing a maximum of flexibility at the price of additional complexity for developers. Part of this complexity arises from the need to keep [=/service workers=] responsive in the face of a single-threaded execution model. As a result, APIs exposed by [=/service workers=] are almost entirely asynchronous, a pattern familiar in other JavaScript contexts but accentuated here by the need to avoid blocking document and resource loading.
Developers using the <a lt="application cache">HTML5 Application Cache</a> have also <a href="http://alistapart.com/article/application-cache-is-a-douchebag">reported that several attributes</a> of the design contribute to <a href="http://alistapart.com/article/application-cache-is-a-douchebag#section6">unrecoverable errors</a>. A key design principle of the [=/service worker=] is that errors should *always* be recoverable. Many details of the update process of [=/service workers=] are designed to avoid these hazards.
[=/Service workers=] are started and kept alive by their relationship to events, not documents. This design borrows heavily from developer and vendor experience with <a>Shared Workers</a> and <a href="https://developer.chrome.com/extensions/background_pages">Chrome Background Pages</a>. A key lesson from these systems is the necessity to time-limit the execution of background processing contexts, both to conserve resources and to ensure that background context loss and restart is top-of-mind for developers. As a result, [=/service workers=] bear more than a passing resemblance to <a href="https://developer.chrome.com/extensions/event_pages">Chrome Event Pages</a>, the successor to Background Pages. [=/Service workers=] may be started by user agents *without an attached document* and may be killed by the user agent at nearly any time. Conceptually, [=/service workers=] can be thought of as Shared Workers that can start, process events, and die without ever handling messages from documents. Developers are advised to keep in mind that [=/service workers=] may be started and killed many times a second.
[=/Service workers=] are generic, event-driven, time-limited script contexts that run at an origin. These properties make them natural endpoints for a range of runtime services that may outlive the context of a particular document, e.g. handling push notifications, background data synchronization, responding to resource requests from other origins, or receiving centralized updates to expensive-to-calculate data (e.g., geolocation or gyroscope).
</section>
<section>
<h2 id="model">Model</h2>
<section dfn-for="service worker">
<h3 id="service-worker-concept">Service Worker</h3>
A <dfn export id="dfn-service-worker" for="">service worker</dfn> is a type of <a>web worker</a>. A [=/service worker=] executes in the registering [=/service worker client=]'s [=/origin=].
A [=/service worker=] has an associated <dfn export id="dfn-state">state</dfn>, which is one of *parsed*, *installing*, *installed*, *activating*, *activated*, and *redundant*. It is initially *parsed*.
A [=/service worker=] has an associated <dfn export id="dfn-script-url">script url</dfn> (a [=/URL=]).
A [=/service worker=] has an associated <dfn export id="dfn-type">type</dfn> which is either "<code>classic</code>" or "<code>module</code>". Unless stated otherwise, it is "<code>classic</code>".
A [=/service worker=] has an associated <dfn export id="dfn-containing-service-worker-registration" lt="registration|containing service worker registration">containing service worker registration</dfn> (a [=/service worker registration=]), which contains itself.
A [=/service worker=] has an associated <dfn export id="dfn-service-worker-id">id</dfn> (an opaque string), which uniquely identifies itself during the lifetime of its <a>containing service worker registration</a>.
A [=/service worker=] has an associated <dfn export id="dfn-service-worker-global-object" for="service worker">global object</dfn> (a {{ServiceWorkerGlobalScope}} object or null).
A [=/service worker=] is dispatched a set of <dfn export id="dfn-lifecycle-events">lifecycle events</dfn>, {{install!!event}} and {{activate!!event}}, and <dfn export id="dfn-functional-events">functional events</dfn> including {{fetch!!event}}.
A [=/service worker=] has an associated <dfn export id="dfn-script-resource">script resource</dfn> (a <a>script</a>), which represents its own script resource. It is initially set to null.
A <a>script resource</a> has an associated <dfn export for="script resource" id="dfn-has-ever-been-evaluated-flag">has ever been evaluated flag</dfn>. It is initially unset.
A <a>script resource</a> has an associated <dfn export for="script resource" id="dfn-https-state">HTTPS state</dfn> (an <a>HTTPS state value</a>). It is initially "<code>none</code>".
A <a>script resource</a> has an associated <dfn export for="script resource" id="dfn-referrer-policy">referrer policy</dfn> (a [=/referrer policy=]). It is initially the empty string.
A [=/service worker=] has an associated <dfn export id="dfn-script-resource-map">script resource map</dfn> which is an <a>ordered map</a> where the keys are [=/URLs=] and the values are [=/responses=].
A [=/service worker=] has an associated <dfn export id="dfn-skip-waiting-flag">skip waiting flag</dfn>. Unless stated otherwise it is unset.
A [=/service worker=] has an associated <dfn export id="dfn-imported-scripts-updated-flag">imported scripts updated flag</dfn>. It is initially unset.
A [=/service worker=] has an associated <dfn export id="dfn-set-of-event-types-to-handle">set of event types to handle</dfn> (a [=ordered set|set=]) whose [=item=] is an <a>event listener</a>'s event type. It is initially an empty set.
A [=/service worker=] has an associated <dfn export id="dfn-set-of-extended-events">set of extended events</dfn> (a [=ordered set|set=]) whose [=item=] is an {{ExtendableEvent}}. It is initially an empty set.
A [=/service worker=] has an associated <dfn export id="dfn-foreign-fetch-scopes">list of foreign fetch scopes</dfn> whose element type is a [=/URL=]. It is initially empty.
A [=/service worker=] has an associated <dfn export id="dfn-foreign-fetch-origins">list of foreign fetch origins</dfn> whose element type is a [=/URL=]. It is initially empty.
<section>
<h4 id="service-worker-lifetime">Lifetime</h4>
The lifetime of a [=/service worker=] is tied to the execution lifetime of events and not references held by [=/service worker clients=] to the {{ServiceWorker}} object.
A user agent *may* <a lt="terminate service worker">terminate</a> [=/service workers=] at any time it:
* Has no event to handle.
* Detects abnormal operation: such as infinite loops and tasks exceeding imposed time limits (if any) while handling the events.
</section>
</section>
<section dfn-for="service worker registration">
<h3 id="service-worker-registration-concept">Service Worker Registration</h3>
A <dfn export id="dfn-service-worker-registration" for="">service worker registration</dfn> is a tuple of a [=service worker registration/scope url=] and a set of [=/service workers=], an <a>installing worker</a>, a <a>waiting worker</a>, and an <a>active worker</a>. A user agent *may* enable many [=/service worker registrations=] at a single origin so long as the [=service worker registration/scope url=] of the [=/service worker registration=] differs. A [=/service worker registration=] of an identical [=service worker registration/scope url=] when one already exists in the user agent causes the existing [=/service worker registration=] to be replaced.
A [=/service worker registration=] has an associated <dfn export id="dfn-scope-url">scope url</dfn> (a [=/URL=]).
A [=/service worker registration=] has an associated <dfn export id="dfn-installing-worker">installing worker</dfn> (a [=/service worker=] or null) whose [=service worker/state=] is *installing*. It is initially set to null.
A [=/service worker registration=] has an associated <dfn export id="dfn-waiting-worker">waiting worker</dfn> (a [=/service worker=] or null) whose [=service worker/state=] is *installed*. It is initially set to null.
A [=/service worker registration=] has an associated <dfn export id="dfn-active-worker">active worker</dfn> (a [=/service worker=] or null) whose [=service worker/state=] is either *activating* or *activated*. It is initially set to null.
A [=/service worker registration=] has an associated <dfn export id="dfn-last-update-check-time">last update check time</dfn>. It is initially set to null.
A [=/service worker registration=] has an associated <dfn export id="dfn-use-cache">use cache</dfn> (a boolean). It is initially set to false.
A [=/service worker registration=] has an associated <dfn export id="dfn-uninstalling-flag">uninstalling flag</dfn>. It is initially unset.
A [=/service worker registration=] has one or more <dfn export id="dfn-service-worker-registration-task-queue">task queues</dfn> that back up the <a>tasks</a> from its <a>active worker</a>'s <a>event loop</a>'s corresponding [=/task queues=]. (The target task sources for this back up operation are the <a>handle fetch task source</a> and the <a>handle functional event task source</a>.) The user agent dumps the <a>active worker</a>'s <a>tasks</a> to the [=/service worker registration=]'s [=service worker registration/task queues=] when the <a>active worker</a> is <a lt="terminate service worker">terminated</a> and <a lt="queue a task">re-queues those tasks</a> to the <a>active worker</a>'s <a>event loop</a>'s corresponding [=/task queues=] when the <a>active worker</a> spins off. Unlike the [=/task queues=] owned by <a>event loops</a>, the [=/service worker registration=]'s [=service worker registration/task queues=] are not processed by any <a>event loops</a> in and of itself.
A [=/service worker registration=] has an associated <dfn export>{{NavigationPreloadManager}}</dfn> object.
A [=/service worker registration=] has an associated <dfn export>navigation preload enabled flag</dfn>. It is initially unset.
A [=/service worker registration=] has an associated <dfn export>navigation preload header value</dfn>, which is a [=byte sequence=]. It is initially set to \`<code>true</code>\`.
<section>
<h4 id="service-worker-registration-lifetime">Lifetime</h4>
A user agent *must* persistently keep a list of <a>registered</a> [=/service worker registrations=] unless otherwise they are explicitly <a>unregistered</a>. A user agent has a <a>scope to registration map</a> that stores the entries of the tuple of [=/service worker registration=]'s [=service worker registration/scope url=] and the corresponding [=/service worker registration=]. The lifetime of [=/service worker registrations=] is beyond that of the {{ServiceWorkerRegistration}} objects which represent them within the lifetime of their corresponding [=/service worker clients=].
</section>
</section>
<section dfn-for="service worker client">
<h3 id="service-worker-client-concept">Service Worker Client</h3>
A <dfn export id="dfn-service-worker-client" for="">service worker client</dfn> is an [=environment=].
A [=/service worker client=] has an algorithm defined as the <dfn export for="service worker client">origin</dfn> that returns the [=/service worker client=]'s [=environment settings object/origin=] if the [=/service worker client=] is an [=environment settings object=], and the [=/service worker client=]'s <a>creation URL</a>'s [=url/origin=] otherwise.
A <dfn export id="dfn-window-client">window client</dfn> is a [=/service worker client=] whose [=environment settings object/global object=] is a {{Window}} object.
A <dfn export id="dfn-dedicatedworker-client">dedicated worker client</dfn> is a [=/service worker client=] whose [=environment settings object/global object=] is a {{DedicatedWorkerGlobalScope}} object.
A <dfn export id="dfn-sharedworker-client">shared worker client</dfn> is a [=/service worker client=] whose [=environment settings object/global object=] is a {{SharedWorkerGlobalScope}} object.
A <dfn export id="dfn-worker-client">worker client</dfn> is either a <a>dedicated worker client</a> or a <a>shared worker client</a>.
</section>
<section>
<h3 id="selection">Selection and Use</h3>
A [=/service worker client=] independently <a lt="selection">selects</a> and <a>uses</a> a [=/service worker registration=] for its own loading and its subresources. The <dfn id="dfn-service-worker-registration-selection">selection</dfn> of a [=/service worker registration=], upon a <a>non-subresource request</a>, is a process of either <a lt="Match Service Worker Registration">matching</a> a [=/service worker registration=] from <a>scope to registration map</a> or inheriting an existing [=/service worker registration=] from its parent or owner context depending on the request's [=request/url=].
When the request's [=request/url=] is not <a lt="is local">local</a>, a [=/service worker client=] <a lt="Match Service Worker Registration">matches</a> a [=/service worker registration=] from <a>scope to registration map</a>. That is, the [=/service worker client=] attempts to consult a [=/service worker registration=] whose [=service worker registration/scope url=] <a lt="Match Service Worker Registration">matches</a> its <a>creation URL</a>.
When the request's [=request/url=] <a>is local</a>, if the [=/service worker client=]'s <a>responsible browsing context</a> is a <a>nested browsing context</a> or the [=/service worker client=] is a <a>worker client</a>, the [=/service worker client=] inherits the [=/service worker registration=] from its <a>parent browsing context</a>'s environment or one of <a>the worker's Documents</a>' environment, respectively, if it exists.
If the <a>selection</a> was successful, the <a lt="selection">selected</a> [=/service worker registration=]'s <a>active worker</a> starts to <dfn id="dfn-control">control</dfn> the [=/service worker client=]. Otherwise, the flow returns to [=/fetch=] where it falls back to the default behavior. When a [=/service worker client=] is <a>controlled</a> by an <a>active worker</a>, it is considered that the [=/service worker client=] is <dfn id="dfn-use" lt="using|uses|used">using</dfn> the <a>active worker</a>'s <a>containing service worker registration</a>.
</section>
<section>
<h3 id="task-sources">Task Sources</h3>
The following additional <a>task sources</a> are used by [=/service workers=].
: The <dfn export id="dfn-handle-fetch-task-source">handle fetch task source</dfn>
:: This <a>task source</a> is used for <a>dispatching</a> {{fetch!!event}} events to [=/service workers=].
: The <dfn export id="dfn-handle-functional-event-task-source">handle functional event task source</dfn>
:: This <a>task source</a> is used for features that <a>dispatch</a> other <a>functional events</a>, e.g. {{push!!event}} events, to [=/service workers=].
Note: A user agent may use a separate task source for each functional event type in order to avoid a head-of-line blocking phenomenon for certain functional events.
</section>
<section>
<h3 id="user-agent-shutdown">User Agent Shutdown</h3>
A user agent *must* maintain the state of its stored [=/service worker registrations=] across restarts with the following rules:
* An <a>installing worker</a> does not persist but is discarded. If the <a>installing worker</a> was the only [=/service worker=] for the [=/service worker registration=], the [=/service worker registration=] is discarded.
* A <a>waiting worker</a> promotes to an <a>active worker</a>.
To attain this, the user agent *must* invoke <a>Handle User Agent Shutdown</a> when it terminates.
</section>
</section>
<section>
<h2 id="document-context">Client Context</h2>
<div class="example">
Bootstrapping with a service worker:
<pre highlight="js">
// scope defaults to the path the script sits in
// "/" in this example
navigator.serviceWorker.register("/serviceworker.js").then(registration => {
console.log("success!");
if (registration.installing) {
registration.installing.postMessage("Howdy from your installing page.");
}
}, err => {
console.error("Installing the worker failed!", err);
});
</pre>
</div>
<section>
<h3 id="serviceworker-interface">{{ServiceWorker}}</h3>
<pre class="idl">
[SecureContext, Exposed=(Window,Worker)]
interface ServiceWorker : EventTarget {
readonly attribute USVString scriptURL;
readonly attribute ServiceWorkerState state;
void postMessage(any message, optional sequence<object> transfer = []);
// event
attribute EventHandler onstatechange;
};
ServiceWorker implements AbstractWorker;
enum ServiceWorkerState {
"installing",
"installed",
"activating",
"activated",
"redundant"
};
</pre>
A {{ServiceWorker}} object represents a [=/service worker=]. Each {{ServiceWorker}} object is associated with a [=/service worker=]. Multiple separate objects implementing the {{ServiceWorker}} interface across documents and workers can all be associated with the same [=/service worker=] simultaneously.
A {{ServiceWorker}} object has an associated {{ServiceWorkerState}} object which is itself associated with [=/service worker=]'s <a>state</a>.
<section>
<h4 id="service-worker-url">{{ServiceWorker/scriptURL}}</h4>
The <dfn attribute for="ServiceWorker"><code>scriptURL</code></dfn> attribute *must* return the [=/service worker=]'s <a lt="URL serializer">serialized</a> [=service worker/script url=].
<div class="example">
For example, consider a document created by a navigation to <code>https://example.com/app.html</code> which <a lt="Match Service Worker Registration">matches</a> via the following registration call which has been previously executed:
<pre highlight="js">
// Script on the page https://example.com/app.html
navigator.serviceWorker.register("/service_worker.js");
</pre>
The value of <code>navigator.serviceWorker.controller.scriptURL</code> will be "<code>https://example.com/service_worker.js</code>".
</div>
</section>
<section>
<h4 id="service-worker-state">{{ServiceWorker/state}}</h4>
The <dfn attribute for="ServiceWorker"><code>state</code></dfn> attribute *must* return the value (in {{ServiceWorkerState}} enumeration) to which it was last set.
</section>
<section algorithm="service-worker-postmessage">
<h4 id="service-worker-postmessage">{{ServiceWorker/postMessage(message, transfer)}}</h4>
The <dfn method for="ServiceWorker"><code>postMessage(|message|, |transfer|)</code></dfn> method *must* run these steps:
1. If the {{ServiceWorker/state}} attribute value of the <a>context object</a> is {{"redundant"}}, <a>throw</a> an "{{InvalidStateError}}" exception and abort these steps.
1. Let |serviceWorker| be the [=/service worker=] represented by the <a>context object</a>.
1. Invoke <a>Run Service Worker</a> algorithm with |serviceWorker| as the argument.
1. Let |destination| be the {{ServiceWorkerGlobalScope}} object associated with |serviceWorker|.
1. Let |targetRealm| be |destination|'s [=global object/Realm=].
1. Let |incumbentSettings| be the <a>incumbent settings object</a>, and |incumbentGlobal| its [=environment settings object/global object=].
1. Let |cloneRecord| be <a abstract-op>StructuredCloneWithTransfer</a>(|message|, |transfer|, |targetRealm|). If this <a>throws</a> an exception, <a lt="throw">rethrow</a> that exception and abort these steps.
1. Let |clonedMessage| be |cloneRecord|.\[[Clone]].
1. Let |newPorts| be a new [=frozen array type|frozen array=] consisting of all {{MessagePort}} objects in |cloneRecord|.\[[TransferList]], if any, maintaining their relative order.
1. <a>Queue a task</a> that runs the following steps:
1. Create an event |e| that uses the {{ExtendableMessageEvent}} interface, with the event type {{message!!event}}, which does not bubble and is not cancelable.
1. Let the {{ExtendableMessageEvent/data}} attribute of |e| be initialized to |clonedMessage|.
1. Let the {{ExtendableMessageEvent/origin}} attribute of |e| be initialized to the <a lt="Unicode serialization of an origin">Unicode serialization</a> of |incumbentSettings|'s [=environment settings object/origin=].
1. If |incumbentGlobal| is a {{ServiceWorkerGlobalScope}} object, let the {{ExtendableMessageEvent/source}} attribute of |e| be initialized to a new {{ServiceWorker}} object that represents |incumbentGlobal|'s [=ServiceWorkerGlobalScope/service worker=].
1. Else if |incumbentGlobal| is a {{Window}} object, let the {{ExtendableMessageEvent/source}} attribute of |e| be initialized to a new {{WindowClient}} object that represents |incumbentGlobal|'s [=/environment settings object=].
1. Else, let it be initialized to a new {{Client}} object that represents the worker associated with |incumbentGlobal|.
1. Let the {{ExtendableMessageEvent/ports}} attribute of |e| be initialized to |newPorts|.
1. <a>Dispatch</a> |e| at |destination|.
1. Invoke [=Update Service Worker Extended Events Set=] with |serviceWorker| and |e|.
The <a>task</a> *must* use the <a>DOM manipulation task source</a>.
</section>
<section>
<h4 id="service-worker-event-handler">Event handler</h4>
The following is the <a>event handler</a> (and its corresponding <a>event handler event type</a>) that *must* be supported, as <a>event handler IDL attributes</a>, by all objects implementing {{ServiceWorker}} interface:
<table class="data">
<thead>
<tr>
<th><a>event handler</a></th>
<th><a>event handler event type</a></th>
</tr>
</thead>
<tbody>
<tr>
<td><dfn attribute for="ServiceWorker"><code>onstatechange</code></dfn></td>
<td>{{ServiceWorker/statechange}}</td>
</tr>
</tbody>
</table>
</section>
</section>
<section>
<h3 id="serviceworkerregistration-interface">{{ServiceWorkerRegistration}}</h3>
<pre class="idl">
[SecureContext, Exposed=(Window,Worker)]
interface ServiceWorkerRegistration : EventTarget {
readonly attribute ServiceWorker? installing;
readonly attribute ServiceWorker? waiting;
readonly attribute ServiceWorker? active;
readonly attribute NavigationPreloadManager navigationPreload;
readonly attribute USVString scope;
readonly attribute boolean useCache;
[NewObject] Promise<void> update();
[NewObject] Promise<boolean> unregister();
// event
attribute EventHandler onupdatefound;
};
</pre>
A {{ServiceWorkerRegistration}} object represents a [=/service worker registration=]. Each {{ServiceWorkerRegistration}} object is associated with a <dfn for="ServiceWorkerRegistration">service worker registration</dfn> (a [=/service worker registration=]). Multiple separate objects implementing the {{ServiceWorkerRegistration}} interface across documents and workers can all be associated with the same [=/service worker registration=] simultaneously.
<section algorithm="navigator-service-worker-installing">
<h4 id="navigator-service-worker-installing">{{ServiceWorkerRegistration/installing}}</h4>
<dfn attribute for="ServiceWorkerRegistration"><code>installing</code></dfn> attribute *must* return the value to which it was last set.
Note: The {{ServiceWorker}} objects returned from this attribute getter that represent the same [=/service worker=] are the same objects.
</section>
<section algorithm="navigator-service-worker-waiting">
<h4 id="navigator-service-worker-waiting">{{ServiceWorkerRegistration/waiting}}</h4>
<dfn attribute for="ServiceWorkerRegistration"><code>waiting</code></dfn> attribute *must* return the value to which it was last set.
Note: The {{ServiceWorker}} objects returned from this attribute getter that represent the same [=/service worker=] are the same objects.
</section>
<section algorithm="navigator-service-worker-active">
<h4 id="navigator-service-worker-active">{{ServiceWorkerRegistration/active}}</h4>
<dfn attribute for="ServiceWorkerRegistration"><code>active</code></dfn> attribute *must* return the value to which it was last set.
Note: The {{ServiceWorker}} objects returned from this attribute getter that represent the same [=/service worker=] are the same objects.
</section>
<section algorithm="service-worker-registration-navigationpreload">
<h4 id="service-worker-registration-navigationpreload">{{ServiceWorkerRegistration/navigationPreload}}</h4>
The <dfn attribute for="ServiceWorkerRegistration"><code>navigationPreload</code></dfn> attribute *must* return [=ServiceWorkerRegistration/service worker registration=]'s {{NavigationPreloadManager}} object.
</section>
<section algorithm="service-worker-registration-scope">
<h4 id="service-worker-registration-scope">{{ServiceWorkerRegistration/scope}}</h4>
The <dfn attribute for="ServiceWorkerRegistration"><code>scope</code></dfn> attribute *must* return [=ServiceWorkerRegistration/service worker registration=]'s <a lt="URL serializer">serialized</a> [=service worker registration/scope url=].
<div class="example">
In the example in [[#service-worker-url]], the value of <code>registration.scope</code>, obtained from <code>navigator.serviceWorker.ready.then(registration => console.log(registration.scope))</code> for example, will be "<code>https://example.com/</code>".
</div>
</section>
<section algorithm="service-worker-registration-usecache">
<h4 id="service-worker-registration-usecache">{{ServiceWorkerRegistration/useCache}}</h4>
The <dfn attribute for="ServiceWorkerRegistration"><code>useCache</code></dfn> attribute *must* return [=ServiceWorkerRegistration/service worker registration=]'s [=service worker registration/use cache=].
</section>
<section algorithm="service-worker-registration-update">
<h4 id="service-worker-registration-update">{{ServiceWorkerRegistration/update()}}</h4>
<dfn method for="ServiceWorkerRegistration"><code>update()</code></dfn> method *must* run these steps:
1. Let |p| be a <a>promise</a>.
1. Let |registration| be the [=ServiceWorkerRegistration/service worker registration=].
1. Let |newestWorker| be the result of running <a>Get Newest Worker</a> algorithm passing |registration| as its argument.
1. If |newestWorker| is null, reject |p| with an "{{InvalidStateError}}" exception and abort these steps.
1. If the <a>context object</a>'s <a>relevant settings object</a>'s [=environment settings object/global object=] |globalObject| is a {{ServiceWorkerGlobalScope}} object, and |globalObject|'s associated [=ServiceWorkerGlobalScope/service worker=]'s <a>state</a> is *installing*, reject |p| with an "{{InvalidStateError}}" exception and abort these steps.
1. Let |job| be the result of running <a>Create Job</a> with *update*, |registration|'s [=service worker registration/scope url=], |newestWorker|'s [=service worker/script url=], |p|, and the <a>context object</a>'s <a>relevant settings object</a>.
1. Set |job|'s <a>worker type</a> to |newestWorker|'s [=service worker/type=].
1. Invoke <a>Schedule Job</a> with |job|.
1. Return |p|.
</section>
<section algorithm="navigator-service-worker-unregister">
<h4 id="navigator-service-worker-unregister">{{ServiceWorkerRegistration/unregister()}}</h4>
Note: The {{ServiceWorkerRegistration/unregister()}} method unregisters the [=/service worker registration=]. It is important to note that the currently <a>controlled</a> [=/service worker client=]'s <a>active service worker</a>'s <a>containing service worker registration</a> is effective until all the [=/service worker clients=] (including itself) using this [=/service worker registration=] unload. That is, the {{ServiceWorkerRegistration/unregister()}} method only affects subsequent <a lt="navigate">navigations</a>.
<dfn method for="ServiceWorkerRegistration"><code>unregister()</code></dfn> method *must* run these steps:
1. Let |p| be a <a>promise</a>.
1. Let |job| be the result of running <a>Create Job</a> with *unregister*, the [=service worker registration/scope url=] of the [=ServiceWorkerRegistration/service worker registration=], null, |p|, and the <a>context object</a>'s <a>relevant settings object</a>.
1. Invoke <a>Schedule Job</a> with |job|.
1. Return |p|.
</section>
<section>
<h4 id="service-worker-registration-event-handler">Event handler</h4>
The following is the <a>event handler</a> (and its corresponding <a>event handler event type</a>) that *must* be supported, as <a>event handler IDL attributes</a>, by all objects implementing {{ServiceWorkerRegistration}} interface:
<table class="data">
<thead>
<tr>
<th><a>event handler</a></th>
<th><a>event handler event type</a></th>
</tr>
</thead>
<tbody>
<tr>
<td><dfn attribute for="ServiceWorkerRegistration"><code>onupdatefound</code></dfn></td>
<td>{{updatefound!!event}}</td>
</tr>
</tbody>
</table>
</section>
</section>
<section>
<h3 id="navigator-serviceworker">{{Navigator/serviceWorker|navigator.serviceWorker}}</h3>
<pre class="idl">
partial interface Navigator {
[SecureContext, SameObject] readonly attribute ServiceWorkerContainer serviceWorker;
};
partial interface WorkerNavigator {
[SecureContext, SameObject] readonly attribute ServiceWorkerContainer serviceWorker;
};
</pre>
The <dfn attribute for="Navigator,WorkerNavigator" id="navigator-service-worker-attribute"><code>serviceWorker</code></dfn> attribute *must* return the {{ServiceWorkerContainer}} object that is associated with the <a>context object</a>.
</section>
<section>
<h3 id="serviceworkercontainer-interface">{{ServiceWorkerContainer}}</h3>
<pre class="idl">
[SecureContext, Exposed=(Window,Worker)]
interface ServiceWorkerContainer : EventTarget {
readonly attribute ServiceWorker? controller;
readonly attribute Promise<ServiceWorkerRegistration> ready;
[NewObject] Promise<ServiceWorkerRegistration> register(USVString scriptURL, optional RegistrationOptions options);
[NewObject] Promise<any> getRegistration(optional USVString clientURL = "");
[NewObject] Promise<sequence<ServiceWorkerRegistration>> getRegistrations();
void startMessages();
// events
attribute EventHandler oncontrollerchange;
attribute EventHandler onmessage; // event.source of message events is ServiceWorker object
};
</pre>
<pre class="idl" id="registration-option-list-dictionary">
dictionary RegistrationOptions {
USVString scope;
WorkerType type = "classic";
boolean useCache = false;
};
</pre>
The user agent *must* create a {{ServiceWorkerContainer}} object when a {{Navigator}} object or a {{WorkerNavigator}} object is created and associate it with that object.
A {{ServiceWorkerContainer}} provides capabilities to register, unregister, and update the [=/service worker registrations=], and provides access to the state of the [=/service worker registrations=] and their associated [=/service workers=].
A {{ServiceWorkerContainer}} has an associated <dfn for="ServiceWorkerContainer">service worker client</dfn>, which is a [=/service worker client=] whose [=environment settings object/global object=] is associated with the {{Navigator}} object or the {{WorkerNavigator}} object that the {{ServiceWorkerContainer}} is retrieved from.
A {{ServiceWorkerContainer}} object has an associated <dfn for="ServiceWorkerContainer">ready promise</dfn> (a <a>promise</a>). It is initially set to a new <a>promise</a>.
A {{ServiceWorkerContainer}} object has a <a>task source</a> called the <dfn export id="dfn-client-message-queue" for="ServiceWorkerContainer">client message queue</dfn>, initially empty. A [=ServiceWorkerContainer/client message queue=] can be enabled or disabled, and is initially disabled. When a {{ServiceWorkerContainer}} object's [=ServiceWorkerContainer/client message queue=] is enabled, the <a>event loop</a> *must* use it as one of its <a>task sources</a>. When the {{ServiceWorkerContainer}} object's <a>relevant global object</a> is a {{Window}} object, all <a>tasks</a> <a lt="queue a task">queued</a> on its [=ServiceWorkerContainer/client message queue=] *must* be associated with its <a>relevant settings object</a>'s <a>responsible document</a>.
<section algorithm="navigator-service-worker-controller">
<h4 id="navigator-service-worker-controller">{{ServiceWorkerContainer/controller}}</h4>
<dfn attribute for="ServiceWorkerContainer"><code>controller</code></dfn> attribute *must* run these steps:
1. Let |client| be the <a>context object</a>'s [=ServiceWorkerContainer/service worker client=].
1. Return the {{ServiceWorker}} object that represents |client|'s <a>active service worker</a>.
Note: {{ServiceWorkerContainer/controller|navigator.serviceWorker.controller}} returns <code>null</code> if the request is a force refresh (shift+refresh). The {{ServiceWorker}} objects returned from this attribute getter that represent the same [=/service worker=] are the same objects.
</section>
<section algorithm="navigator-service-worker-ready">
<h4 id="navigator-service-worker-ready">{{ServiceWorkerContainer/ready}}</h4>
<dfn attribute for="ServiceWorkerContainer"><code>ready</code></dfn> attribute *must* run these steps:
1. If the <a>context object</a>'s [=ServiceWorkerContainer/ready promise=] is settled, return the <a>context object</a>'s [=ServiceWorkerContainer/ready promise=].
1. Let |client| be the <a>context object</a>'s [=ServiceWorkerContainer/service worker client=].
1. Let |registration| be null.
1. Let |clientURL| be |client|'s <a>creation URL</a>.
1. Run the following substeps <a>in parallel</a>:
1. *CheckRegistration*: If the result of running <a>Match Service Worker Registration</a> algorithm with |clientURL| as its argument is not null, then:
1. Set |registration| to the result value.
1. Else:
1. Wait until <a>scope to registration map</a> has a new entry.
1. Jump to the step labeled *CheckRegistration*.
1. If |registration|'s <a>active worker</a> is null, wait until |registration|'s <a>active worker</a> changes.
Note: Implementers should consider this condition is met when the corresponding registration request gets to the step 6 of <a>Activate</a> algorithm.
1. Resolve <a>context object</a>'s [=ServiceWorkerContainer/ready promise=] with the {{ServiceWorkerRegistration}} object which represents |registration|.
1. Return <a>context object</a>'s [=ServiceWorkerContainer/ready promise=].
Note: When the {{ServiceWorkerContainer/ready}} attribute is accessed, the returned <a>promise</a> will never reject. Instead, it waits until the <a>promise</a> resolves with a [=/service worker registration=] that has an <a>active worker</a>.
</section>
<section algorithm="navigator-service-worker-register">
<h4 id="navigator-service-worker-register">{{ServiceWorkerContainer/register(scriptURL, options)}}</h4>
Note: The {{ServiceWorkerContainer/register(scriptURL, options)}} method creates or updates a [=/service worker registration=] for the given [=service worker registration/scope url=]. If successful, a [=/service worker registration=] ties the provided |scriptURL| to a [=service worker registration/scope url=], which is subsequently used for <a lt="handle fetch">navigation matching</a>.
<dfn method for="ServiceWorkerContainer"><code>register(|scriptURL|, |options|)</code></dfn> method *must* run these steps:
1. Let |p| be a <a>promise</a>.
1. Let |client| be the <a>context object</a>'s [=ServiceWorkerContainer/service worker client=].
1. Let |scriptURL| be the result of <a lt="URL parser">parsing</a> |scriptURL| with the <a>context object</a>'s <a>relevant settings object</a>'s <a>API base URL</a>.
1. Let |scopeURL| be null.
1. If |options|.{{RegistrationOptions/scope}} is <a>present</a>, set |scopeURL| to the result of <a lt="URL parser">parsing</a> |options|.{{RegistrationOptions/scope}} with the <a>context object</a>'s <a>relevant settings object</a>'s <a>API base URL</a>.
1. Invoke [=Start Register=] with |scopeURL|, |scriptURL|, |p|, |client|, |client|'s <a>creation URL</a>, |options|.{{RegistrationOptions/type}}, and |options|.{{RegistrationOptions/useCache}}.
1. Return |p|.
</section>
<section algorithm="navigator-service-worker-getRegistration">
<h4 id="navigator-service-worker-getRegistration">{{ServiceWorkerContainer/getRegistration(clientURL)}}</h4>
<dfn method for="ServiceWorkerContainer"><code>getRegistration(|clientURL|)</code></dfn> method *must* run these steps:
1. Let |client| be the <a>context object</a>'s [=ServiceWorkerContainer/service worker client=].
1. Let |clientURL| be the result of <a lt="URL parser">parsing</a> |clientURL| with the <a>context object</a>'s <a>relevant settings object</a>'s <a>API base URL</a>.
1. If |clientURL| is failure, return a <a>promise</a> rejected with a <code>TypeError</code>.
1. If the [=environment settings object/origin=] of |clientURL| is not |client|'s [=environment settings object/origin=], return a |promise| rejected with a "{{SecurityError}}" exception.
1. Let |promise| be a new <a>promise</a>.
1. Run the following substeps <a>in parallel</a>:
1. Let |registration| be the result of running <a>Match Service Worker Registration</a> algorithm with |clientURL| as its argument.
1. If |registration| is not null, then:
1. Resolve |promise| with the {{ServiceWorkerRegistration}} object which represents |registration|.
1. Else:
1. Resolve |promise| with undefined.
1. Return |promise|.
</section>
<section algorithm="navigator-service-worker-getRegistrations">
<h4 id="navigator-service-worker-getRegistrations">{{ServiceWorkerContainer/getRegistrations()}}</h4>
<dfn method for="ServiceWorkerContainer"><code>getRegistrations()</code></dfn> method *must* run these steps:
1. Let |client| be the <a>context object</a>'s [=ServiceWorkerContainer/service worker client=].
1. Let |promise| be a new <a>promise</a>.
1. Run the following substeps <a>in parallel</a>:
1. Let |array| be an empty array.
1. [=map/For each=] |key| → |value| of <a>scope to registration map</a>:
1. If the [=url/origin=] of the result of <a lt="URL parser">parsing</a> |key| is the <a lt="same origin">same</a> as |client|'s [=environment settings object/origin=], and |value|'s <a>uninstalling flag</a> is unset, add the {{ServiceWorkerRegistration}} object associated with |value| to the |array|.
1. Resolve |promise| with |array|.
1. Return |promise|.
</section>
<section algorithm="navigator-service-worker-startMessages">
<h4 id="navigator-service-worker-startMessages">{{ServiceWorkerContainer/startMessages()}}</h4>
<dfn method for="ServiceWorkerContainer"><code>startMessages()</code></dfn> method *must* enable the <a>context object</a>'s [=ServiceWorkerContainer/client message queue=] if it is not enabled.
</section>
<section>
<h4 id="service-worker-container-event-handlers">Event handlers</h4>
The following are the <a>event handlers</a> (and their corresponding <a>event handler event types</a>) that *must* be supported, as <a>event handler IDL attributes</a>, by all objects implementing the {{ServiceWorkerContainer}} interface:
<table class="data">
<thead>
<tr>
<th><a>event handler</a></th>
<th><a>event handler event type</a></th>
</tr>
</thead>
<tbody>
<tr>
<td><dfn attribute for="ServiceWorkerContainer"><code>oncontrollerchange</code></dfn></td>
<td>{{ServiceWorkerContainer/controllerchange!!event}}</td>
</tr>
<tr>
<td><dfn attribute for="ServiceWorkerContainer"><code>onmessage</code></dfn></td>
<td>{{ServiceWorkerContainer/message!!event}}</td>
</tr>
</tbody>
</table>
The first time the <a>context object</a>'s {{ServiceWorkerContainer/onmessage}} IDL attribute is set, its [=ServiceWorkerContainer/client message queue=] *must* be enabled.
</section>
</section>
<section>
<h3 id="document-context-events">Events</h3>
The following event is dispatched on {{ServiceWorker}} object:
<table class="data">
<thead>
<tr>
<th>Event name</th>
<th>Interface</th>
<th>Dispatched when…</th>
</tr>
</thead>
<tbody>
<tr>
<td><dfn event for="ServiceWorker"><code>statechange</code></dfn></td>
<td>{{Event}}</td>
<td>The {{ServiceWorker/state}} attribute of the {{ServiceWorker}} object is changed.</td>
</tr>
</tbody>
</table>
The following event is dispatched on {{ServiceWorkerRegistration}} object:
<table class="data">
<thead>
<tr>
<th>Event name</th>
<th>Interface</th>
<th>Dispatched when…</th>
</tr>
</thead>
<tbody>
<tr>
<td><dfn event for="ServiceWorkerRegistration" id="service-worker-registration-updatefound-event"><code>updatefound</code></dfn></td>
<td>{{Event}}</td>
<td>The [=ServiceWorkerRegistration/service worker registration=]'s <a>installing worker</a> changes. (See step 8 of the <a>Install</a> algorithm.)</td>
</tr>
</tbody>
</table>
The following events are dispatched on {{ServiceWorkerContainer}} object:
<table class="data" dfn-for="ServiceWorkerContainer">
<thead>
<tr>
<th>Event name</th>
<th>Interface</th>
<th>Dispatched when…</th>
</tr>
</thead>
<tbody>
<tr>
<td><dfn event id="service-worker-container-controllerchange-event"><code>controllerchange</code></dfn></td>
<td>{{Event}}</td>
<td>The [=ServiceWorkerContainer/service worker client=]'s <a>active service worker</a> changes. (See step 9.2 of the <a>Activate</a> algorithm. The <a>skip waiting flag</a> of a [=/service worker=] causes <a lt="activate">activation</a> of the [=/service worker registration=] to occur while [=/service worker clients=] are <a>using</a> the [=/service worker registration=], {{ServiceWorkerContainer/controller|navigator.serviceWorker.controller}} immediately reflects the <a>active worker</a> as the [=/service worker=] that <a>controls</a> the [=/service worker client=].)</td>
</tr>
</tbody>
</table>
</section>
</section>
<section>
<h3 id="navigation-preload-manager">{{NavigationPreloadManager}}</h3>
<pre class="idl">
[SecureContext, Exposed=(Window,Worker)]
interface NavigationPreloadManager {
Promise<void> enable();
Promise<void> disable();
Promise<void> setHeaderValue(ByteString value);
Promise<NavigationPreloadState> getState();
};
dictionary NavigationPreloadState {
boolean enabled = false;
ByteString headerValue;
};
</pre>
<section algorithm="navigation-preload-manager-enable">
<h4 id="navigation-preload-manager-enable">{{NavigationPreloadManager/enable()}}</h4>
The <dfn method for="NavigationPreloadManager"><code>enable()</code></dfn> method, when invoked, *must* return a new [=promise=] |promise| and run the following steps [=in parallel=]:
1. Let |registration| be the [=context object=]'s associated [=/service worker registration=].
1. If |registration|'s [=active worker=] is null, [=reject=] |promise| with an "{{InvalidStateError}}" exception, and abort these steps.
1. Set |registration|'s [=navigation preload enabled flag=].
1. [=Resolve=] |promise| with undefined.
</section>
<section algorithm="navigation-preload-manager-disable">
<h4 id="navigation-preload-manager-disable">{{NavigationPreloadManager/disable()}}</h4>
The <dfn method for="NavigationPreloadManager"><code>disable()</code></dfn> method, when invoked, *must* return a new [=promise=] |promise| and run the following steps [=in parallel=]:
1. Let |registration| be the [=context object=]'s associated [=/service worker registration=].
1. If |registration|'s [=active worker=] is null, [=reject=] |promise| with an "{{InvalidStateError}}" exception, and abort these steps.
1. Unset |registration|'s [=navigation preload enabled flag=].
1. [=Resolve=] |promise| with undefined.
</section>
<section algorithm="navigation-preload-manager-setheadervalue">
<h4 id="navigation-preload-manager-setheadervalue">{{NavigationPreloadManager/setHeaderValue(value)}}</h4>
The <dfn method for="NavigationPreloadManager"><code>setHeaderValue(|value|)</code></dfn> method, when invoked, *must* return [=a new promise=] |promise| and run the following steps [=in parallel=]:
1. Let |registration| be the [=context object=]'s associated [=/service worker registration=].
1. If |registration|'s [=active worker=] is null, [=reject=] |promise| with an "{{InvalidStateError}}" exception, and abort these steps.
1. Set |registration|'s [=navigation preload header value=] to |value|.
1. [=Resolve=] |promise| with undefined.
</section>
<section algorithm="navigation-preload-manager-getstate">
<h4 id="navigation-preload-manager-getstate">{{NavigationPreloadManager/getState()}}</h4>
The <dfn method for="NavigationPreloadManager"><code>getState()</code></dfn> method, when invoked, *must* return [=a new promise=] |promise| and run the following steps [=in parallel=]:
1. Let |registration| be the [=context object=]'s associated [=/service worker registration=].
1. Let |state| be a new {{NavigationPreloadState}} dictionary.
1. If |registration|'s [=navigation preload enabled flag=] is set, set |state|'s {{NavigationPreloadState/enabled}} dictionary member to true.
1. Set |state|'s {{NavigationPreloadState/headerValue}} dictionary member to the |registration|'s [=navigation preload header value=].
1. [=Resolve=] |promise| with |state|.
</section>
</section>
<section>
<h2 id="execution-context">Execution Context</h2>
<div class="example">
Serving Cached Resources:
<pre highlight="js">
// caching.js
self.addEventListener("install", event => {
event.waitUntil(
// Open a cache of resources.
caches.open("shell-v1").then(cache => {
// Begins the process of fetching them.
// The coast is only clear when all the resources are ready.
return cache.addAll([
"/app.html",
"/assets/v1/base.css",
"/assets/v1/app.js",
"/assets/v1/logo.png",
"/assets/v1/intro_video.webm"
]);
})
);
});
self.addEventListener("fetch", event => {
// No "fetch" events are dispatched to the service worker until it
// successfully installs and activates.
// All operations on caches are async, including matching URLs, so we use
// promises heavily. e.respondWith() even takes promises to enable this:
event.respondWith(
caches.match(e.request).then(response => {
return response || fetch(e.request);
}).catch(() => {
return caches.match("/fallback.html");
})
);
});
</pre>
</div>
<section>
<h3 id="serviceworkerglobalscope-interface">{{ServiceWorkerGlobalScope}}</h3>
<pre class="idl">
[Global=(Worker,ServiceWorker), Exposed=ServiceWorker]
interface ServiceWorkerGlobalScope : WorkerGlobalScope {
[SameObject] readonly attribute Clients clients;
[SameObject] readonly attribute ServiceWorkerRegistration registration;
[NewObject] Promise<void> skipWaiting();
attribute EventHandler oninstall;
attribute EventHandler onactivate;
attribute EventHandler onfetch;
attribute EventHandler onforeignfetch;
// event
attribute EventHandler onmessage; // event.source of the message events is Client object
};
</pre>
A {{ServiceWorkerGlobalScope}} object represents the global execution context of a [=/service worker=]. A {{ServiceWorkerGlobalScope}} object has an associated <dfn for="ServiceWorkerGlobalScope">service worker</dfn> (a [=/service worker=]). A {{ServiceWorkerGlobalScope}} object has an associated <dfn for="ServiceWorkerGlobalScope">force bypass cache for importscripts flag</dfn>. It is initially unset.
Note: {{ServiceWorkerGlobalScope}} object provides generic, event-driven, time-limited script execution contexts that run at an origin. Once successfully <a>registered</a>, a [=/service worker=] is started, kept alive and killed by their relationship to events, not [=/service worker clients=]. Any type of synchronous requests must not be initiated inside of a [=/service worker=].
<section>
<h4 id="service-worker-global-scope-clients">{{ServiceWorkerGlobalScope/clients}}</h4>
<dfn attribute for="ServiceWorkerGlobalScope"><code>clients</code></dfn> attribute *must* return the {{Clients}} object that is associated with the <a>context object</a>.
</section>
<section>
<h4 id="service-worker-global-scope-registration">{{ServiceWorkerGlobalScope/registration}}</h4>
The <dfn attribute for="ServiceWorkerGlobalScope"><code>registration</code></dfn> attribute *must* return the {{ServiceWorkerRegistration}} object that represents the [=ServiceWorkerGlobalScope/service worker=]'s <a>containing service worker registration</a>.
</section>
<section algorithm="service-worker-global-scope-skipwaiting">
<h4 id="service-worker-global-scope-skipwaiting">{{ServiceWorkerGlobalScope/skipWaiting()}}</h4>
Note: The {{ServiceWorkerGlobalScope/skipWaiting()}} method allows this [=/service worker=] to progress from the [=service worker/registration=]'s <a lt="waiting worker">waiting</a> position to <a lt="active worker">active</a> even while [=/service worker clients=] are <a>using</a> the [=service worker/registration=].
<dfn method for="ServiceWorkerGlobalScope"><code>skipWaiting()</code></dfn> method *must* run these steps:
1. Let |promise| be a new <a>promise</a>.
1. Run the following substeps <a>in parallel</a>:
1. Set [=ServiceWorkerGlobalScope/service worker=]'s <a>skip waiting flag</a>.
1. Invoke [=Try Activate=] with [=ServiceWorkerGlobalScope/service worker=]'s [=containing service worker registration=].
1. Resolve |promise| with undefined.
1. Return |promise|.
</section>
<section>
<h4 id="service-worker-global-scope-event-handlers">Event handlers</h4>
The following are the <a>event handlers</a> (and their corresponding <a>event handler event types</a>) that *must* be supported, as <a>event handler IDL attributes</a>, by all objects implementing the {{ServiceWorkerGlobalScope}} interface:
<table class="data">
<thead>
<tr>
<th><a>event handler</a></th>
<th><a>event handler event type</a></th>
</tr>
</thead>
<tbody>
<tr>
<td><dfn attribute for="ServiceWorkerGlobalScope"><code>oninstall</code></dfn></td>
<td>{{install!!event}}</td>
</tr>
<tr>
<td><dfn attribute for="ServiceWorkerGlobalScope"><code>onactivate</code></dfn></td>
<td>{{activate!!event}}</td>
</tr>
<tr>
<td><dfn attribute for="ServiceWorkerGlobalScope"><code>onfetch</code></dfn></td>
<td>{{fetch!!event}}</td>
</tr>
<tr>
<td><dfn attribute for="ServiceWorkerGlobalScope"><code>onforeignfetch</code></dfn></td>
<td>{{foreignfetch!!event}}</td>
</tr>
<tr>
<td><dfn attribute for="ServiceWorkerGlobalScope"><code>onmessage</code></dfn></td>
<td>{{message!!event}}</td>
</tr>
</tbody>
</table>
</section>
</section>
<section>
<h3 id="client-interface">{{Client}}</h3>
<pre class="idl">
[Exposed=ServiceWorker]
interface Client {
readonly attribute USVString url;
readonly attribute DOMString id;
readonly attribute ClientType type;
readonly attribute boolean reserved;
void postMessage(any message, optional sequence<object> transfer = []);
};
[Exposed=ServiceWorker]
interface WindowClient : Client {
readonly attribute VisibilityState visibilityState;
readonly attribute boolean focused;
[SameObject] readonly attribute FrozenArray<USVString> ancestorOrigins;
[NewObject] Promise<WindowClient> focus();
[NewObject] Promise<WindowClient> navigate(USVString url);
};
</pre>
A {{Client}} object has an associated <dfn for="Client">service worker client</dfn> (a [=/service worker client=]).
A {{Client}} object has an associated <dfn for="Client">reserved state</dfn>, which is either true or false.
A {{WindowClient}} object has an associated <dfn id="dfn-service-worker-client-visibilitystate">visibility state</dfn>, which is one of {{Document/visibilityState}} attribute value.
A {{WindowClient}} object has an associated <dfn id="dfn-service-worker-client-focusstate">focus state</dfn>, which is either true or false (initially false).
A {{WindowClient}} object has an associated <dfn for="WindowClient">ancestor origins array</dfn>.
<section>
<h4 id="client-url">{{Client/url}}</h4>
The <dfn attribute for="Client"><code>url</code></dfn> attribute *must* return the <a>context object</a>'s associated [=Client/service worker client=]'s <a lt="URL serializer">serialized</a> <a>creation URL</a>.
</section>
<section>
<h4 id="client-id">{{Client/id}}</h4>
The <dfn attribute for="Client"><code>id</code></dfn> attribute *must* return its associated [=Client/service worker client=]'s [=environment/id=].
</section>
<section>
<h4 id="client-type">{{Client/type}}</h4>
The <dfn attribute for="Client"><code>type</code></dfn> attribute *must* run these steps: