aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/serviceworker/statechange_event/index.html
blob: c14f15619895ea3ba088b2fe7208c575e4cd1a16 (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
---
title: ServiceWorker.onstatechange
slug: Web/API/ServiceWorker/statechange_event
translation_of: Web/API/ServiceWorker/onstatechange
original_slug: Web/API/ServiceWorker/onstatechange
---
<div>{{SeeCompatTable}}{{APIRef("Service Workers API")}}</div>

<p>一个 {{domxref("EventListener")}} 联动的属性,其会被任何stagechange类型事件抛出时联动; 它也基本上能在任何时候{{domxref("ServiceWorker.state")}} 改变时被抛出.</p>

<h2 id="语法">语法</h2>

<pre class="syntaxbox">ServiceWorker.onstatechange = function(statechangeevent) { ... }
ServiceWorker.addEventListener('statechange', function(statechangeevent) { ... } )</pre>

<h2 id="示例">示例</h2>

<p>这段代码出自 <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/registration-events/index.html">service worker registration-events sample</a> (<a href="https://googlechrome.github.io/samples/service-worker/registration-events/">live demo</a>). 它会监听 {{domxref("ServiceWorker.state")}} 的改变并返回它的值.</p>

<pre class="brush: js">var serviceWorker;
if (registration.installing) {
  serviceWorker = registration.installing;
  document.querySelector('#kind').textContent = 'installing';
} else if (registration.waiting) {
  serviceWorker = registration.waiting;
  document.querySelector('#kind').textContent = 'waiting';
} else if (registration.active) {
  serviceWorker = registration.active;
  document.querySelector('#kind').textContent = 'active';
}

if (serviceWorker) {
  logState(serviceWorker.state);
  serviceWorker.addEventListener('statechange', function(e) {
  logState(e.target.state);
  });
}</pre>

<p>注意当<code>statechange</code> 抛出时, service worker的引用可能已经改变。例如:</p>

<pre class="brush: js">navigator.serviceWorker.register(..).then(function(swr) {
  swr.installing.state == "installing"
  swr.installing.onstatechange = function() {
    swr.installing == null;
    // At this point, swr.waiting OR swr.active might be true. This is because the statechange
    // event gets queued, meanwhile the underlying worker may have gone into the waiting
    // state and will be immediately activated if possible.
  }
})</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-onstatechange-attribute', 'ServiceWorker.onstatechange')}}</td>
   <td>{{Spec2('Service Workers')}}</td>
   <td>Initial definition</td>
  </tr>
 </tbody>
</table>

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

{{Compat("api.ServiceWorker.onstatechange")}}