aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/serviceworkerglobalscope/index.html
blob: f51a873d4374db6712b50f9ac04f9a0374868382 (plain)
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
---
title: ServiceWorkerGlobalScope
slug: Web/API/ServiceWorkerGlobalScope
translation_of: Web/API/ServiceWorkerGlobalScope
---
<div>{{APIRef("Service Workers API")}}</div>

<p><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a> 的<code>ServiceWorkerGlobalScope</code> 接口,代表一个service worker的全局执行上下文。</p>

<p>开发者应该知道, ServiceWorker 的状态在结束/重启的循环中不是一直保持不变的,所以每个事件处理器应该设定一个默认的全局状态。</p>

<p>一旦成功地注册了service worker,为了节省内存和处理器,它将在他的状态达到了空闲的时候被终止。 一个在激活状态的service worker为了响应事件是可以自动重启的,就像这两个方法, {{domxref("ServiceWorkerGlobalScope.onfetch")}} 或者{{domxref("ServiceWorkerGlobalScope.onmessage")}}.</p>

<p>此外, 在service worker中, 同步请求是被禁止的 - 只有异步请求,如方法{{domxref("GlobalFetch.fetch", "fetch()")}} 才被允许.</p>

<p>该接口继承自 {{domxref("WorkerGlobalScope")}} 接口, 以及其父类 {{domxref("EventTarget")}}, 因此继承属性来自 {{domxref("WindowTimers")}}, {{domxref("WindowBase64")}}, 和 {{domxref("WindowEventHandlers")}}.</p>

<p>{{InheritanceDiagram(700, 85, 20)}}</p>

<h2 id="属性">属性</h2>

<dl>
 <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>
 <dt>{{domxref("ServiceWorkerGlobalScope.caches")}} {{readonlyinline}}</dt>
 <dd>Contains the {{domxref("CacheStorage")}} object associated with the service worker.</dd>
</dl>

<h3 id="Event_handlers">Event handlers</h3>

<dl>
 <dt>{{domxref("ServiceWorkerGlobalScope.onactivate")}}</dt>
 <dd>An event handler fired whenever an {{Event("activate")}} event occurs — when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.active")}} worker.</dd>
 <dt>{{domxref("ServiceWorkerGlobalScope.onfetch")}}</dt>
 <dd>An event handler fired whenever a {{Event("fetch")}} event occurs — when a {{domxref("GlobalFetch.fetch", "fetch()")}} is called.</dd>
 <dt>{{domxref("ServiceWorkerGlobalScope.oninstall")}}</dt>
 <dd>An event handler fired whenever an {{Event("install")}} event occurs — when a {{domxref("ServiceWorkerRegistration")}} acquires a new {{domxref("ServiceWorkerRegistration.installing")}} worker.</dd>
 <dt>{{domxref("ServiceWorkerGlobalScope.onmessage")}}</dt>
 <dd>An event handler fired whenever a {{Event("message")}} event 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.</dd>
 <dt>{{domxref("ServiceWorkerGlobalScope.onnotificationclick")}}</dt>
 <dd>An event handler fired whenever a {{Event("notificationclick")}} event occurs — when a user clicks on a displayed notification.</dd>
 <dt>{{domxref("ServiceWorkerGlobalScope.onnotificationclose")}}</dt>
 <dd>An event handler fired whenever a {{Event("notificationclose")}} event occurs — when a user closes a displayed notification.</dd>
 <dt>{{domxref("ServiceWorkerGlobalScope.onpush")}}</dt>
 <dd>An event handler fired whenever a {{Event("push")}} event occurs — when a server push notification is received.</dd>
 <dt>{{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange")}}</dt>
 <dd>An event handler fired whenever a {{Event("pushsubscriptionchange")}} event occurs — when a push subscription has been invalidated, or is about to be invalidated (e.g. when a push service sets an expiration time.)</dd>
 <dt>{{domxref("ServiceWorkerGlobalScope.onsync")}}</dt>
 <dd>An event handler fired whenever a {{Event("SyncEvent")}} event occurs. This is 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. </dd>
</dl>

<h2 id="方法">方法</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("GlobalFetch")}}. 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="示例">示例</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 notranslate">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="规范">规范</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">规范</th>
   <th scope="col">状态</th>
   <th scope="col">备注</th>
  </tr>
  <tr>
   <td>{{SpecName('Service Workers', '#service-worker-global-scope', 'ServiceWorkerGlobalScope')}}</td>
   <td>{{Spec2('Service Workers')}}</td>
   <td>Initial definition</td>
  </tr>
  <tr>
   <td>{{SpecName('Fetch', '#concept-fetch', 'Fetch')}}</td>
   <td>{{Spec2('Fetch')}}</td>
   <td>Adds the {{domxref("ServiceWorkerGlobalScope.fetch", "fetch")}} method.</td>
  </tr>
  <tr>
   <td>{{SpecName('Push API', '#widl-ServiceWorkerGlobalScope-onpush', 'onpush')}}</td>
   <td>{{Spec2('Push API')}}</td>
   <td>Adds the {{domxref("ServiceWorkerGlobalScope.onpush", "onpush")}} and {{domxref("ServiceWorkerGlobalScope.onpushsubscriptionchange", "onpushsubscriptionchange")}} event handlers.</td>
  </tr>
  <tr>
   <td>{{SpecName('Web Notifications','#dom-serviceworkerglobalscope-onnotificationclick','onnotificationclick')}}</td>
   <td>{{Spec2('Web Notifications')}}</td>
   <td>Adds the {{domxref("ServiceWorkerGlobalScope.onnotificationclick", "onnotificationclick")}} event handler.</td>
  </tr>
  <tr>
   <td>{{SpecName('Background Sync','#sync-event','onsync')}}</td>
   <td>{{Spec2('Background Sync')}}</td>
   <td>Adds the {{domxref("ServiceWorkerGlobalScope.onsync","onsync")}} event.</td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容性">浏览器兼容性</h2>

<div>{{CompatibilityTable}}</div>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari (WebKit)</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatChrome(40.0)}}</td>
   <td>{{CompatGeckoDesktop("44.0")}}<sup>[1]</sup></td>
   <td>{{CompatNo}}</td>
   <td>24</td>
   <td>{{CompatNo}}</td>
  </tr>
  <tr>
   <td><code>onnotificationclick</code></td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoDesktop("42.0")}}<sup>[1]</sup></td>
   <td>{{CompatNo}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatNo}}</td>
  </tr>
  <tr>
   <td><code>onsync</code></td>
   <td>{{CompatChrome(49.0)}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Android Webview</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>Firefox OS</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
   <th>Chrome for Android</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatGeckoMobile("44.0")}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatChrome(40.0)}}</td>
  </tr>
  <tr>
   <td><code>onnotificationclick</code></td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatGeckoMobile("42.0")}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
  <tr>
   <td><code>onsync</code></td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatChrome(49.0)}}</td>
  </tr>
 </tbody>
</table>
</div>

<p>[1] Service workers (and <a href="/en-US/docs/Web/API/Push_API">Push</a>) have been disabled in the <a href="https://www.mozilla.org/en-US/firefox/organizations/">Firefox 45 and 52 Extended Support Releases</a> (ESR.)</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 class="external external-icon" href="https://github.com/mdn/sw-test">Service workers basic code example</a></li>
 <li><a class="external external-icon" href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li>
 <li>{{jsxref("Promise")}}</li>
 <li><a href="/en-US/docs/Web/Guide/Performance/Using_web_workers">Using web workers</a></li>
</ul>