-
Notifications
You must be signed in to change notification settings - Fork 317
/
Copy pathindex.bs
4204 lines (3383 loc) · 280 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: Monica Chintala, w3cid 160353, Microsoft, [email protected]
Editor: Yoshisato Yanagisawa, w3cid 142513, Google, [email protected]
Former Editor: Alex Russell, Google, [email protected]
Former Editor: Jake Archibald, w3cid 76394, Google, [email protected]
Former Editor: Jungkee Song, Microsoft‚ represented Samsung until April 2018, [email protected]
Former Editor: Marijn Kruisselbrink, w3cid 72440, Google, [email protected]
Repository: w3c/ServiceWorker
Group: webapps
!Tests: <a href=https://github.com/web-platform-tests/wpt/tree/master/service-workers>web-platform-tests service-workers/</a> (<a href=https://github.com/web-platform-tests/wpt/labels/service-workers>ongoing work</a>)
Status Text: This is a living document. Readers need to be aware that this specification may include unimplemented features, and details that may change. <a href="https://w3c.github.io/ServiceWorker/v1/">Service Workers 1</a> is a version that is advancing toward a W3C Recommendation.
Abstract: The core of this specification is a worker that wakes to receive events. This provides an event destination that can be used when other destinations would be inappropriate, or no other destination exists.
Abstract:
Abstract: For example, to allow the developer to decide how a page should be fetched, an event needs to dispatch potentially before any other execution contexts exist for that origin. To react to a push message, or completion of a persistent download, the context that originally registered interest may no longer exist. In these cases, the service worker is the ideal event destination.
Abstract:
Abstract: This specification also provides a [=handle fetch|fetch event=], and a [[#cache-objects|request and response store]] similar in design to the HTTP cache, which makes it easier to build offline-enabled web applications.
Markup Shorthands: css no, markdown yes
</pre>
<pre class="link-defaults">
spec: html;
type: element; text: link
type: dfn
text: task queues; for: /
text: event loop; for: /
text: script
spec: dom;
type: interface; text: Document
type: dfn; text: event
spec: fetch;
type: dfn
for: /; text: fetch
text: empty
text: fetch controller
spec: infra;
type: dfn;
text: list
text: queue
for: set; text: append
for: list; text: append
spec: webidl;
type: dfn;
text: resolve;
spec:csp-next; type:dfn; text:enforced
spec:urlpattern; type:dfn; text:match
</pre>
<pre class="anchors">
spec: push; urlPrefix: https://w3c.github.io/push-api/
type: event
text: push; url: pushevent-interface
spec: ecma-262; urlPrefix: https://tc39.es/ecma262/
type: abstract-op
text: NormalCompletion; url: sec-normalcompletion
text: ThrowCompletion; url: sec-throwcompletion
text: IsCallable; url: sec-iscallable
text: Get; url: sec-get-o-p
type: dfn
text: agent;
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
text: abrupt completion; url: sec-completion-record-specification-type
text: Completion; url: sec-completion-record-specification-type
text: Module Record; url: sec-abstract-module-records
text: Cyclic Module Record; url: sec-cyclic-module-records
text: function body; url: prod-FunctionBody
url: sec-ecmascript-language-statements-and-declarations
text: statement
text: declaration
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
urlPrefix: interaction.html
text: visibilityState; for: Document; url: page-visibility
type: dfn
urlPrefix: nav-history-apis.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
urlPrefix: browsers.html
text: creating a policy container from a fetch response
urlPrefix: webappapis.html
text: module map; url: module-map
text: resolve a module specifier; url: resolve-a-module-specifier
type: enum
urlPrefix: interaction.html
text: VisibilityState; url: page-visibility
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: rfc8288; urlPrefix: https://tools.ietf.org/html/rfc8288
type: dfn
text: link context; url: section-3.2
text: target attribute; url: section-3.4
text: target attributes; url: section-3.4
text: link target; url: section-3.1
spec: rfc7230; urlPrefix: https://datatracker.ietf.org/doc/html/rfc7230
type: dfn
text: field-value; for: http; url: section-3.2
spec: rfc7231; urlPrefix: https://datatracker.ietf.org/doc/html/rfc7231
type: dfn
text: Vary; url: section-7.1.4
spec: storage; urlPrefix: https://storage.spec.whatwg.org/
type: dfn
text: storage key; url: storage-key
text: obtain a storage key; url: obtain-a-storage-key
text: storage key/equals; url: storage-key-equals
</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 href="https://www.w3.org/TR/2014/REC-html5-20141028/browsers.html#appcache">HTML5 Application Cache</a> have also <a href="https://alistapart.com/article/application-cache-is-a-douchebag/">reported that several attributes</a> of the design contribute to <a href="https://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 [[HTML#shared-workers-and-the-sharedworker-interface|shared workers]] and <a href="https://developer.chrome.com/docs/extensions/mv2/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/docs/apps/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-global-object" for="service worker">global object</dfn> (a {{ServiceWorkerGlobalScope}} object or null).
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-policy-container">policy container</dfn> (a [=/policy container=]). It is initially a new policy container.
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-set-of-used-scripts">set of used scripts</dfn> (a [=ordered set|set=]) whose [=list/item=] is a [=/URL=]. It is initially a new [=ordered set|set=].
Note: The [=set of used scripts=] is only used to prune unused resources from a new worker's map after installation, that were populated based on the old worker's map during the update check.
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-classic-scripts-imported-flag">classic scripts imported 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 [=list/item=] is an <a>event listener</a>'s event type. It is initially a new [=ordered set|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 [=list/item=] is an {{ExtendableEvent}}. It is initially a new [=ordered set|set=].
A [=/service worker=] has an associated <dfn>start status</dfn> which can be null or a [=Completion=]. It is initially null.
A [=/service worker=] has an associated <dfn>all fetch listeners are empty flag</dfn>. It is initially unset.
A [=/service worker=] has an associated <dfn>list of router rules</dfn> (a [=list=] of {{RouterRule}}s). It is initially an empty [=list=].
A [=/service worker=] is said to be <dfn>running</dfn> if its [=event loop=] is running.
A [=/service worker=] has an associated <dfn>[[service worker queue]]</dfn> (a [=parallel queue=]).
<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>
<h4 id="service-worker-events">Events</h4>
The Service Workers specification defines <dfn export id="dfn-service-worker-events">service worker events</dfn> (each of which is an [=event=]) that include (see the <a href="#execution-context-events">list</a>):
* <dfn export id="dfn-lifecycle-events">Lifecycle events</dfn>: {{ServiceWorkerGlobalScope/install!!event}} and {{ServiceWorkerGlobalScope/activate!!event}}.
* <dfn export id="dfn-functional-events">Functional events</dfn>: {{ServiceWorkerGlobalScope/fetch!!event}} and the [=events=] defined by other specifications that <a href="#extensibility">extend</a> the Service Workers specification. (See the <a href="#execution-context-events">list</a>.)
* {{ServiceWorkerGlobalScope/message!!event}} and {{ServiceWorkerGlobalScope/messageerror!!event}}.
</section>
</section>
<section>
<h3 id="service-worker-timing">Service Worker Timing</h3>
Service workers mark certain points in time that are later exposed by the <a interface lt="PerformanceNavigationTiming">navigation timing</a> API.
A <dfn export>service worker timing info</dfn> is a [=/struct=]. It has the following [=struct/items=]:
<section dfn-for="service worker timing info">
: <dfn export>start time</dfn>
:: A {{DOMHighResTimeStamp}}, initially 0.
: <dfn export>fetch event dispatch time</dfn>
:: A {{DOMHighResTimeStamp}}, initially 0.
</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=], a [=/storage key=], 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 for="service worker registration">storage key</dfn> (a [=/storage key=]).
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=] is said to be <dfn>stale</dfn> if the registration's [=last update check time=] is non-null and the time difference in seconds calculated by the current time minus the registration's [=last update check time=] is greater than 86400.
A [=/service worker registration=] has an associated <dfn export id="dfn-update-via-cache">update via cache mode</dfn>, which is "`imports`", "`all`", or "`none`". It is initially set to "`imports`".
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>\`.
A [=/service worker registration=] is said to be <dfn export id="dfn-service-worker-registration-unregistered">unregistered</dfn> if [=registration map=][this [=/service worker registration=]'s ([=service worker registration/storage key=], [=URL serializer|serialized=] [=service worker registration/scope url=])] is not this [=/service worker registration=].
<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>registration map</a> that stores the entries of the tuple of [=/service worker registration=]'s ([=service worker registration/storage key=], [=URL serializer|serialized=] [=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 associated <dfn export>discarded flag</dfn>. It is initially unset.
Each [=/service worker client=] has the following [=environment discarding steps=]:
1. Set |client|'s [=discarded flag=].
Note: Implementations can discard clients whose [=discarded flag=] is set.
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="control-and-use">Control and Use</h3>
A [=/service worker client=] has an [=active service worker=] that serves its own loading and its subresources. When a [=/service worker client=] has a non-null [=active service worker=], it is said to be <dfn id="dfn-control" lt="controlling|controls|controlled">controlled</dfn> by that [=active service worker=]. When a [=/service worker client=] is [=controlled=] by a [=/service worker=], it is said that the [=/service worker client=] is <dfn id="dfn-use" lt="using|uses|used">using</dfn> the [=/service worker=]’s [=containing service worker registration=].
A [=/service worker client=]'s [=active service worker=] is determined as explained in the following subsections.
*The rest of the section is non-normative.*
Issue: The behavior in this section is not fully specified yet and will be specified in [HTML Standard](https://html.spec.whatwg.org). The work is tracked by the [issue](https://github.com/w3c/ServiceWorker/issues/765) and the [pull request](https://github.com/whatwg/html/pull/2809).
<section>
<h4 id="control-and-use-window-client">The window client case</h4>
A [=window client=] is [created](https://html.spec.whatwg.org/#set-up-a-window-environment-settings-object) when a [=/browsing context=] is [created](https://html.spec.whatwg.org/#creating-a-new-browsing-context) and when it [=navigates=].
When a [=window client=] is [created](https://html.spec.whatwg.org/#set-up-a-window-environment-settings-object) in the process of a [=/browsing context=] [creation](https://html.spec.whatwg.org/#creating-a-new-browsing-context):
If the [=/browsing context=]'s initial [=active document=]'s [=/origin=] is an [=opaque origin=], the [=window client=]'s [=active service worker=] is set to null.
Otherwise, it is set to the creator [=/document=]'s [=/service worker client=]'s [=active service worker=].
When a [=window client=] is [created](https://html.spec.whatwg.org/#set-up-a-window-environment-settings-object) in the process of the [=/browsing context=]'s [=navigate|navigation=]:
If the [=fetch=] is routed through [=/HTTP fetch=], the [=window client=]'s [=active service worker=] is set to the result of the <a lt="Match Service Worker Registration">service worker registration matching</a>.
Otherwise, if the created [=/document=]'s [=/origin=] is an [=opaque origin=] or not the [=same origin|same=] as its creator [=/document=]'s [=/origin=], the [=window client=]'s [=active service worker=] is set to null.
Otherwise, it is set to the creator [=/document=]'s [=/service worker client=]'s [=active service worker=].
Note: For an initial replacement [=navigate|navigation=], the initial [=window client=] that was [created](https://html.spec.whatwg.org/#set-up-a-window-environment-settings-object) when the [=/browsing context=] was [created](https://html.spec.whatwg.org/#creating-a-new-browsing-context) is reused, but the [=active service worker=] is determined by the same behavior as above.
Note: <a element-attr for=iframe lt=sandbox>Sandboxed</a> <{iframe}>s without the sandboxing directives, `allow-same-origin` and `allow-scripts`, result in having the [=active service worker=] value of null as their [=/origin=] is an [=opaque origin=].
</section>
<section>
<h4 id="control-and-use-worker-client">The worker client case</h4>
A [=worker client=] is <a href="https://html.spec.whatwg.org/#set-up-a-worker-environment-settings-object">created</a> when the user agent [=run a worker|runs a worker=].
When the [=worker client=] is created:
When the [=fetch=] is routed through [=/HTTP fetch=], the [=worker client=]'s [=active service worker=] is set to the result of the <a lt="Match Service Worker Registration">service worker registration matching</a>.
Otherwise, if the [=worker client=]'s [=service worker client/origin=] is an [=opaque origin=], or the [=/request=]'s [=request/URL=] is a [=blob URL=] and the [=worker client=]'s [=service worker client/origin=] is not the [=same origin|same=] as the [=/origin=] of the last [=set/item=] in the [=worker client=]'s [=/global object=]'s [=owner set=], the [=worker client=]'s [=active service worker=] is set to null.
Otherwise, it is set to the [=active service worker=] of the [=environment settings object=] of the last [=set/item=] in the [=worker client=]'s [=/global object=]'s [=owner set=].
</section>
Note: [=Window clients=] and [=worker clients=] with a [data: URL](https://datatracker.ietf.org/doc/html/rfc2397#section-2) result in having the [=active service worker=] value of null as their [=/origin=] is an [=opaque origin=]. [=Window clients=] and [=worker clients=] with a [=blob URL=] can inherit the [=active service worker=] of their creator [=/document=] or owner, but if the [=/request=]'s [=request/origin=] is not the [=same origin|same=] as the [=/origin=] of their creator [=/document=] or owner, the [=active service worker=] is set to null.
</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;
undefined postMessage(any message, sequence<object> transfer);
undefined postMessage(any message, optional StructuredSerializeOptions options = {});
// event
attribute EventHandler onstatechange;
};
ServiceWorker includes AbstractWorker;
enum ServiceWorkerState {
"parsed",
"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 [=service worker/state=].
<section>
<h4 id="service-worker-creation">Getting {{ServiceWorker}} instances</h4>
An [=environment settings object=] has a <dfn for="environment settings object">service worker object map</dfn>, a [=/map=] where the [=map/keys=] are [=/service workers=] and the [=map/values=] are {{ServiceWorker}} objects.
<section algorithm="service-worker-creation-algorithm">
To <dfn lt="get the service worker object|getting the service worker object">get the service worker object</dfn> representing |serviceWorker| (a [=/service worker=]) in |environment| (an [=environment settings object=]), run these steps:
1. Let |objectMap| be |environment|'s [=environment settings object/service worker object map=].
1. If |objectMap|[|serviceWorker|] does not [=map/exist=], then:
1. Let |serviceWorkerObj| be a new {{ServiceWorker}} in |environment|'s [=environment settings object/Realm=], and associate it with |serviceWorker|.
1. Set |serviceWorkerObj|'s {{ServiceWorker/state}} to |serviceWorker|'s [=service worker/state=].
1. Set |objectMap|[|serviceWorker|] to |serviceWorkerObj|.
1. Return |objectMap|[|serviceWorker|].
</section>
</section>
<section>
<h4 id="service-worker-url">{{ServiceWorker/scriptURL}}</h4>
The <dfn attribute for="ServiceWorker"><code>scriptURL</code></dfn> getter steps are to 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 steps are:
1. Let |options| be «[ "transfer" → |transfer| ]».
1. Invoke {{ServiceWorker/postMessage(message, options)}} with |message| and |options| as the arguments.
</section>
<section algorithm="service-worker-postmessage-options">
<h4 id="service-worker-postmessage-options">{{ServiceWorker/postMessage(message, options)}}</h4>
The <dfn method for="ServiceWorker"><code>postMessage(|message|, |options|)</code></dfn> method steps are:
1. Let |serviceWorker| be the [=/service worker=] represented by [=this=].
1. Let |incumbentSettings| be the [=incumbent settings object=].
1. Let |incumbentGlobal| be |incumbentSettings|'s [=environment settings object/global object=].
1. Let |serializeWithTransferResult| be <a abstract-op>StructuredSerializeWithTransfer</a>(|message|, |options|["{{StructuredSerializeOptions/transfer}}"]). Rethrow any exceptions.
1. If the result of running the [=Should Skip Event=] algorithm with "message" and |serviceWorker| is true, then return.
1. Run these substeps [=in parallel=]:
1. If the result of running the [=Run Service Worker=] algorithm with |serviceWorker| is *failure*, then return.
1. [=Queue a task=] on the [=DOM manipulation task source=] to run the following steps:
1. Let |source| be determined by switching on the type of |incumbentGlobal|:
<dl class="switch">
<dt>{{ServiceWorkerGlobalScope}}</dt>
<dd>The result of [=getting the service worker object=] that represents |incumbentGlobal|'s [=ServiceWorkerGlobalScope/service worker=] in the [=relevant settings object=] of |serviceWorker|'s [=service worker/global object=].</dd>
<dt>{{Window}}</dt>
<dd>a new {{WindowClient}} object that represents |incumbentGlobal|'s [=relevant settings object=].</dd>
<dt>Otherwise</dt>
<dd>a new {{Client}} object that represents |incumbentGlobal|'s associated worker</dd>
</dl>
1. Let |origin| be the [=serialization of an origin|serialization=] of |incumbentSettings|'s [=environment settings object/origin=].
1. Let |destination| be the {{ServiceWorkerGlobalScope}} object associated with |serviceWorker|.
1. Let |deserializeRecord| be <a abstract-op>StructuredDeserializeWithTransfer</a>(|serializeWithTransferResult|, |destination|'s [=global object/Realm=]).
If this throws an exception, let |e| be the result of [=creating an event=] named {{ServiceWorkerGlobalScope/messageerror!!event}}, using {{ExtendableMessageEvent}}, with the {{ExtendableMessageEvent/origin}} attribute initialized to |origin| and the {{ExtendableMessageEvent/source}} attribute initialized to |source|.
1. Else:
1. Let |messageClone| be |deserializeRecord|.\[[Deserialized]].
1. Let |newPorts| be a new [=frozen array type|frozen array=] consisting of all {{MessagePort}} objects in |deserializeRecord|.\[[TransferredValues]], if any, maintaining their relative order.
1. Let |e| be the result of [=creating an event=] named {{ServiceWorkerGlobalScope/message!!event}}, using {{ExtendableMessageEvent}}, with the {{ExtendableMessageEvent/origin}} attribute initialized to |origin|, the {{ExtendableMessageEvent/source}} attribute initialized to |source|, the {{ExtendableMessageEvent/data}} attribute initialized to |messageClone|, and the {{ExtendableMessageEvent/ports}} attribute initialized to |newPorts|.
1. [=Dispatch=] |e| at |destination|.
1. Invoke [=Update Service Worker Extended Events Set=] with |serviceWorker| and |e|.
</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;
[SameObject] readonly attribute NavigationPreloadManager navigationPreload;
readonly attribute USVString scope;
readonly attribute ServiceWorkerUpdateViaCache updateViaCache;
[NewObject] Promise<undefined> update();
[NewObject] Promise<boolean> unregister();
// event
attribute EventHandler onupdatefound;
};
enum ServiceWorkerUpdateViaCache {
"imports",
"all",
"none"
};
</pre>
A {{ServiceWorkerRegistration}} has a <dfn export for="ServiceWorkerRegistration">service worker registration</dfn> (a [=/service worker registration=]).
<section>
<h4 id="service-worker-registration-creation">Getting {{ServiceWorkerRegistration}} instances</h4>
An [=environment settings object=] has a <dfn for="environment settings object">service worker registration object map</dfn>, a [=/map=] where the [=map/keys=] are [=/service worker registrations=] and the [=map/values=] are {{ServiceWorkerRegistration}} objects.
<section algorithm="service-worker-registration-creation-algorithm">
To <dfn lt="get the service worker registration object|getting the service worker registration object">get the service worker registration object</dfn> representing |registration| (a [=/service worker registration=]) in |environment| (an [=environment settings object=]), run these steps:
1. Let |objectMap| be |environment|'s [=environment settings object/service worker registration object map=].
1. If |objectMap|[|registration|] does not [=map/exist=], then:
1. Let |registrationObject| be a new {{ServiceWorkerRegistration}} in |environment|'s [=environment settings object/Realm=].
1. Set |registrationObject|'s [=ServiceWorkerRegistration/service worker registration=] to |registration|.
1. Set |registrationObject|'s {{ServiceWorkerRegistration/installing}} attribute to null.
1. Set |registrationObject|'s {{ServiceWorkerRegistration/waiting}} attribute to null.
1. Set |registrationObject|'s {{ServiceWorkerRegistration/active}} attribute to null.
1. If |registration|'s [=service worker registration/installing worker=] is not null, then set |registrationObject|'s {{ServiceWorkerRegistration/installing}} attribute to the result of [=getting the service worker object=] that represents |registration|'s [=service worker registration/installing worker=] in |environment|.
1. If |registration|'s [=service worker registration/waiting worker=] is not null, then set |registrationObject|'s {{ServiceWorkerRegistration/waiting}} attribute to the result of [=getting the service worker object=] that represents |registration|'s [=service worker registration/waiting worker=] in |environment|.
1. If |registration|'s [=service worker registration/active worker=] is not null, then set |registrationObject|'s {{ServiceWorkerRegistration/active}} attribute to the result of [=getting the service worker object=] that represents |registration|'s [=service worker registration/active worker=] in |environment|.
1. Set |objectMap|[|registration|] to |registrationObject|.
1. Return |objectMap|[|registration|].
</section>
</section>
<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: Within a [=environment settings object/Realm=], there is only one {{ServiceWorker}} object per associated [=/service worker=].
</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: Within a [=environment settings object/Realm=], there is only one {{ServiceWorker}} object per associated [=/service worker=].
</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: Within a [=environment settings object/Realm=], there is only one {{ServiceWorker}} object per associated [=/service worker=].
</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> getter steps are to return the [=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> getter steps are to return the [=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-updateviacache">
<h4 id="service-worker-registration-updateviacache">{{ServiceWorkerRegistration/updateViaCache}}</h4>
The <dfn attribute for="ServiceWorkerRegistration"><code>updateViaCache</code></dfn> getter steps are to return the [=ServiceWorkerRegistration/service worker registration=]'s [=service worker registration/update via cache mode=].
</section>
<section algorithm="service-worker-registration-update">
<h4 id="service-worker-registration-update">{{ServiceWorkerRegistration/update()}}</h4>
The <dfn method for="ServiceWorkerRegistration"><code>update()</code></dfn> method steps are:
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, return [=a promise rejected with=] an "{{InvalidStateError}}" {{DOMException}} and abort these steps.
1. If [=this=]'s [=relevant global object=] |globalObject| is a {{ServiceWorkerGlobalScope}} object, and |globalObject|'s associated [=ServiceWorkerGlobalScope/service worker=]'s [=service worker/state=] is "`installing`", return [=a promise rejected with=] an "{{InvalidStateError}}" {{DOMException}} and abort these steps.
1. Let |promise| be a <a>promise</a>.
1. Let |job| be the result of running <a>Create Job</a> with *update*, |registration|'s [=service worker registration/storage key=], |registration|'s [=service worker registration/scope url=], |newestWorker|'s [=service worker/script url=], |promise|, and [=this=]'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 |promise|.
</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 [=controlled=] [=/service worker client=]'s [=active service worker=]'s [=containing service worker registration=] 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 [=navigate|navigations=].
The <dfn method for="ServiceWorkerRegistration"><code>unregister()</code></dfn> method steps are:
1. Let |registration| be the [=ServiceWorkerRegistration/service worker registration=].
1. Let |promise| be [=a new promise=].
1. Let |job| be the result of running [=Create Job=] with *unregister*, |registration|'s [=service worker registration/storage key=], |registration|'s [=service worker registration/scope url=], null, |promise|, and [=this=]'s <a>relevant settings object</a>.
1. Invoke <a>Schedule Job</a> with |job|.
1. Return |promise|.
</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> getter steps are to return the {{ServiceWorkerContainer}} object that is associated with [=this=].
</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((TrustedScriptURL or USVString) scriptURL, optional RegistrationOptions options = {});
[NewObject] Promise<(ServiceWorkerRegistration or undefined)> getRegistration(optional USVString clientURL = "");
[NewObject] Promise<FrozenArray<ServiceWorkerRegistration>> getRegistrations();
undefined startMessages();
// events
attribute EventHandler oncontrollerchange;
attribute EventHandler onmessage; // event.source of message events is ServiceWorker object
attribute EventHandler onmessageerror;
};
</pre>
<pre class="idl" id="registration-option-list-dictionary">
dictionary RegistrationOptions {
USVString scope;
WorkerType type = "classic";
ServiceWorkerUpdateViaCache updateViaCache = "imports";
};
</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 [=promise=] or null). It is initially null.
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 [=associated document=].
<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 [=this=]'s [=ServiceWorkerContainer/service worker client=].
1. If |client|'s [=active service worker=] is null, then return null.
1. Return the result of [=getting the service worker object=] that represents |client|'s [=active service worker=] in [=this=]'s [=relevant settings object=].
Note: {{ServiceWorkerContainer/controller|navigator.serviceWorker.controller}} returns <code>null</code> if the request is a force refresh (shift+refresh).
</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 [=this=]'s [=ServiceWorkerContainer/ready promise=] is null, then set [=this=]'s [=ServiceWorkerContainer/ready promise=] to [=a new promise=].
1. Let |readyPromise| be [=this=]'s [=ServiceWorkerContainer/ready promise=].
1. If |readyPromise| is pending, run the following substeps [=in parallel=]:
1. Let |client| by [=this=]'s [=ServiceWorkerContainer/service worker client=].
1. Let |storage key| be the result of running [=obtain a storage key=] given client.
1. Let |registration| be the result of running [=Match Service Worker Registration=] given |storage key| and |client|'s [=creation URL=].
1. If |registration| is not null, and |registration|'s [=active worker=] is not null, [=queue a task=] on |readyPromise|'s [=relevant settings object=]'s [=responsible event loop=], using the [=DOM manipulation task source=], to resolve |readyPromise| with the result of [=getting the service worker registration object=] that represents |registration| in |readyPromise|'s [=relevant settings object=].
1. Return |readyPromise|.
Note: The returned [=ServiceWorkerContainer/ready promise=] will never reject. If it does not resolve in this algorithm, it will eventually resolve when a matching [=/service worker registration=] is registered and its [=active worker=] is set. (See the relevant [Activate algorithm step](#activate-resolve-ready-step).)
</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>.
The <dfn method for="ServiceWorkerContainer"><code>register(|scriptURL|, |options|)</code></dfn> method steps are:
1. Let |p| be a <a>promise</a>.
1. Set |scriptURL| to the result of invoking [$Get Trusted Type compliant string$] with {{TrustedScriptURL}}, [=this=]'s [=relevant global object=], |scriptURL|, "ServiceWorkerContainer register", and "script".
1. Let |client| be [=this=]'s [=ServiceWorkerContainer/service worker client=].
1. Let |scriptURL| be the result of <a lt="URL parser">parsing</a> |scriptURL| with [=this=]'s <a>relevant settings object</a>'s <a>API base URL</a>.
1. Let |scopeURL| be null.
1. If |options|["{{RegistrationOptions/scope}}"] [=map/exists=], set |scopeURL| to the result of <a lt="URL parser">parsing</a> |options|["{{RegistrationOptions/scope}}"] with [=this=]'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/updateViaCache}}"].
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 steps are:
1. Let |client| be [=this=]'s [=ServiceWorkerContainer/service worker client=].
1. Let |storage key| be the result of running [=obtain a storage key=] given |client|.
1. Let |clientURL| be the result of <a lt="URL parser">parsing</a> |clientURL| with [=this=]'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. Set |clientURL|'s [=url/fragment=] to null.
1. If the [=environment settings object/origin=] of |clientURL| is not |client|'s [=environment settings object/origin=], return a |promise| rejected with a "{{SecurityError}}" {{DOMException}}.
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> given |storage key| and |clientURL|.
1. If |registration| is null, resolve |promise| with undefined and abort these steps.
1. Resolve |promise| with the result of [=getting the service worker registration object=] that represents |registration| in |promise|'s [=relevant settings object=].
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 steps are:
1. Let |client| be [=this=]'s [=ServiceWorkerContainer/service worker client=].
1. Let |client storage key| be the result of running [=obtain a storage key=] given |client|.
1. Let |promise| be [=a new promise=].
1. Run the following steps [=in parallel=]:
1. Let |registrations| be a new [=list=].
1. [=list/For each=] (|storage key|, <var ignore>scope</var>) → |registration| of [=registration map=]:
1. If |storage key| [=storage key/equals=] |client storage key|, then [=append=] |registration| to |registrations|.
1. [=Queue a task=] on |promise|'s [=relevant settings object=]'s [=responsible event loop=], using the [=DOM manipulation task source=], to run the following steps:
1. Let |registrationObjects| be a new [=list=].
1. [=list/For each=] |registration| of |registrations|:
1. Let |registrationObj| be the result of [=getting the service worker registration object=] that represents |registration| in |promise|'s [=relevant settings object=].
1. [=list/Append=] |registrationObj| to |registrationObjects|.
1. Resolve |promise| with [=create a frozen array|a new frozen array of=] |registrationObjects| in |promise|'s [=relevant Realm=].
1. Return |promise|.
</section>
<section algorithm="navigator-service-worker-startMessages">
<h4 id="navigator-service-worker-startMessages">{{ServiceWorkerContainer/startMessages()}}</h4>
The <dfn method for="ServiceWorkerContainer"><code>startMessages()</code></dfn> method steps are to enable [=this=]'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>
<tr>
<td><dfn attribute for="ServiceWorkerContainer"><code>onmessageerror</code></dfn></td>
<td>{{ServiceWorkerContainer/messageerror!!event}}</td>
</tr>
</tbody>
</table>
The first time the {{ServiceWorkerContainer/onmessage}} setter steps are performed, enable [=this=]'s [=ServiceWorkerContainer/client message queue=].
</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>
<tr>
<td><dfn event id="service-worker-container-message-event"><code>message</code></dfn></td>
<td>{{Event}}</td>
<td>The [=ServiceWorkerContainer/service worker client=] receives a message from a [=/service worker=]. See {{Client/postMessage(message, options)}}.</td>
</tr>
<tr>
<td><dfn event id="service-worker-container-messageerror-event"><code>messageerror</code></dfn></td>
<td>{{Event}}</td>
<td>The [=ServiceWorkerContainer/service worker client=] is sent a message that cannot be deserialized from a [=/service worker=]. See {{Client/postMessage(message, options)}}.</td>
</tr>
</tbody>
</table>
</section>
</section>
<section>
<h3 id="navigation-preload-manager">{{NavigationPreloadManager}}</h3>
<pre class="idl">
[SecureContext, Exposed=(Window,Worker)]
interface NavigationPreloadManager {
Promise<undefined> enable();
Promise<undefined> disable();
Promise<undefined> 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 steps are:
1. Let |promise| be [=a new promise=].
1. Run the following steps [=in parallel=]:
1. Let |registration| be [=this=]'s associated [=/service worker registration=].
1. If |registration|'s [=active worker=] is null, [=reject=] |promise| with an "{{InvalidStateError}}" {{DOMException}}, and abort these steps.
1. Set |registration|'s [=navigation preload enabled flag=].
1. Resolve |promise| with undefined.
1. Return |promise|.
</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 steps are:
1. Let |promise| be [=a new promise=].
1. Run the following steps [=in parallel=]:
1. Let |registration| be [=this=]'s associated [=/service worker registration=].
1. If |registration|'s [=active worker=] is null, [=reject=] |promise| with an "{{InvalidStateError}}" {{DOMException}}, and abort these steps.
1. Unset |registration|'s [=navigation preload enabled flag=].
1. Resolve |promise| with undefined.
1. Return |promise|.
</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 steps are:
1. Let |promise| be [=a new promise=].
1. Run the following steps [=in parallel=]: