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
|
---
title: ServiceWorkerGlobalScope
slug: Web/API/ServiceWorkerGlobalScope
tags:
- API
- Interface
- NeedsTranslation
- Offline
- Reference
- Service Workers
- ServiceWorkerGlobalScope
- TopicStub
translation_of: Web/API/ServiceWorkerGlobalScope
---
<div>{{APIRef("Service Workers API")}}</div>
<p>The <strong><code>ServiceWorkerGlobalScope</code></strong> interface of the <a href="/en-US/docs/Web/API/Service_Worker_API">Service Worker API</a> represents the global execution context of a service worker.</p>
<p>Developers should keep in mind that the ServiceWorker state is not persisted across the termination/restart cycle, so each event handler should assume it's being invoked with a bare, default global state.</p>
<p>Once successfully registered, a service worker can and will be terminated when idle to conserve memory and processor power. An active service worker is automatically restarted to respond to events, such as {{domxref("ServiceWorkerGlobalScope.onfetch")}} or {{domxref("ServiceWorkerGlobalScope.onmessage")}}.</p>
<p>Additionally, synchronous requests are not allowed from within a service worker — only asynchronous requests, like those initiated via the {{domxref("GlobalFetch.fetch", "fetch()")}} method, can be used.</p>
<p>This interface inherits from the {{domxref("WorkerGlobalScope")}} interface, and its parent {{domxref("EventTarget")}}, and therefore implements properties from {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, and {{domxref("WindowEventHandlers")}}.</p>
<p>{{InheritanceDiagram(700, 85, 20)}}</p>
<h2 id="Properties">Properties</h2>
<dl>
<dt>{{domxref("ServiceWorkerGlobalScope.caches")}} {{readonlyinline}}</dt>
<dd>Contains the {{domxref("CacheStorage")}} object associated with the service worker.</dd>
<dt>{{domxref("ServiceWorkerGlobalScope.clients")}} {{readonlyinline}}</dt>
<dd>Contains the {{domxref("Clients")}} object associated with the service worker.</dd>
<dt>{{domxref("ServiceWorkerGlobalScope.registration")}} {{readonlyinline}}</dt>
<dd>Contains the {{domxref("ServiceWorkerRegistration")}} object that represents the service worker's registration.</dd>
</dl>
<h2 id="Events">Events</h2>
<dl>
<dt>{{domxref("ServiceWorkerGlobalScope/activate_event", "activate")}}</dt>
<dd>Occurs when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active")}} worker.<br>
Also available via the {{domxref("ServiceWorkerGlobalScope.onactivate")}} property.</dd>
<dt>{{domxref("ServiceWorkerGlobalScope/contentdelete_event", "contentdelete")}}</dt>
<dd>Occurs when an item is removed from the {{domxref("ContentIndex", "Content Index")}}.<br>
Also available via the {{domxref("ServiceWorkerGlobalScope.oncontentdelete")}} property.</dd>
<dt><code>fetch</code></dt>
<dd>Occurs when a {{domxref("GlobalFetch.fetch", "fetch()")}} is called.<br>
Also available via the {{domxref("ServiceWorkerGlobalScope.onfetch")}} property.</dd>
<dt>{{domxref("ServiceWorkerGlobalScope/install_event", "install")}}</dt>
<dd>Occurs when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.installing")}} worker.<br>
Also available via the {{domxref("ServiceWorkerGlobalScope.oninstall")}} property.</dd>
<dt>{{domxref("ServiceWorkerGlobalScope/message_event", "message")}}</dt>
<dd>Occurs when incoming messages are received. Controlled pages can use the {{domxref("MessagePort.postMessage()")}} method to send messages to service workers. The service worker can optionally send a response back via the {{domxref("MessagePort")}} exposed in <a href="https://html.spec.whatwg.org/multipage/comms.html#messageport"><code>event.data.port</code></a>, corresponding to the controlled page.<br>
Also available via the {{domxref("ServiceWorkerGlobalScope.onmessage")}} property.</dd>
<dt>{{domxref("ServiceWorkerGlobalScope/notificationclick_event", "notificationclick")}}</dt>
<dd>Occurs when a user clicks on a displayed notification.<br>
Also available via the {{domxref("ServiceWorkerGlobalScope.onnotificationclick")}} property.</dd>
<dt><code>notificationclose</code></dt>
<dd>Occurs — when a user closes a displayed notification.<br>
Also available via the {{domxref("ServiceWorkerGlobalScope.onnotificationclose")}} property.</dd>
<dt>{{domxref("ServiceWorkerGlobalScope/push_event", "push")}}</dt>
<dd>Occurs when a server push notification is received.<br>
Also available via the {{domxref("ServiceWorkerGlobalScope.onpush")}} property.</dd>
<dt>{{domxref("ServiceWorkerGlobalScope/pushsubscriptionchange_event", "pushsubscriptionchange")}}</dt>
<dd>Occurs when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time).<br>
Also available via the {{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}} property.</dd>
<dt><code>sync</code></dt>
<dd>Triggered when a call to {{domxref("SyncManager.register")}} is made from a service worker client page. The attempt to sync is made either immediately if the network is available or as soon as the network becomes available.<br>
Also available via the {{domxref("ServiceWorkerGlobalScope.onsync")}} property.</dd>
</dl>
<h2 id="Methods">Methods</h2>
<dl>
<dt>{{domxref("ServiceWorkerGlobalScope.skipWaiting()")}}</dt>
<dd>Allows the current service worker registration to progress from waiting to active state while service worker clients are using it.</dd>
</dl>
<p><code>ServiceWorkerGlobalScope</code> implements {{domxref("WorkerGlobalScope")}} — which implements {{domxref("WindowOrWorkerGlobalScope")}}. Therefore it also has the following property available to it:</p>
<dl>
<dt>{{domxref("GlobalFetch.fetch()")}}</dt>
<dd>Starts the process of fetching a resource. This returns a promise that resolves to the {{domxref("Response")}} object representing the response to your request. This algorithm is the entry point for the fetch handling handed to the service worker context.</dd>
</dl>
<h2 id="Examples">Examples</h2>
<p>This code snippet is from the <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/prefetch/service-worker.js">service worker prefetch sample</a> (see <a href="https://googlechrome.github.io/samples/service-worker/prefetch/">prefetch example live</a>.) The {{domxref("ServiceWorkerGlobalScope.onfetch")}} event handler listens for the <code>fetch</code> event. When fired, the code returns a promise that resolves to the first matching request in the {{domxref("Cache")}} object. If no match is found, the code fetches a response from the network.</p>
<p>The code also handles exceptions thrown from the {{domxref("GlobalFetch.fetch", "fetch()")}} operation. Note that an HTTP error response (e.g., 404) will not trigger an exception. It will return a normal response object that has the appropriate error code set.</p>
<pre class="brush: js">self.addEventListener('fetch', function(event) {
console.log('Handling fetch event for', event.request.url);
event.respondWith(
caches.match(event.request).then(function(response) {
if (response) {
console.log('Found response in cache:', response);
return response;
}
console.log('No response found in cache. About to fetch from network...');
return fetch(event.request).then(function(response) {
console.log('Response from network is:', response);
return response;
}, function(error) {
console.error('Fetching failed:', error);
throw error;
});
})
);
});</pre>
<h2 id="Specifications">Specifications</h2>
<table class="standard-table">
<thead>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{SpecName('Service Workers', '#serviceworkerglobalscope-interface', 'ServiceWorkerGlobalScope')}}</td>
<td>{{Spec2('Service Workers')}}</td>
<td>Initial definition</td>
</tr>
</tbody>
</table>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<p>{{Compat("api.ServiceWorkerGlobalScope")}}</p>
<h2 id="See_also">See also</h2>
<ul>
<li><a href="/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a></li>
<li><a href="https://github.com/mdn/sw-test">Service workers basic code example</a></li>
<li><a href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li>
<li>{{jsxref("Promise")}}</li>
</ul>
|