--- title: ServiceWorker slug: Web/API/ServiceWorker tags: - API - Draft - Experimental - Service Worker - 离线 translation_of: Web/API/ServiceWorker ---
一个ServiceWorker对象在 {{domxref("ServiceWorkerRegistration.active")}} 属性和 {{domxref("ServiceWorkerContainer.controller")}} 属性中可用 — 这是一个激活并在控制页面的service worker(service worker成功注册,被控页面已经重新加载完毕.)
ServiceWorker接口被分配了一系列生命周期事件 --- 安装和激活 --- 以及功能型的事件,包括 fetch.一个ServiceWorker对象有一个与之关联的 {{domxref("ServiceWorker.state")}},指示着它的生命周期.
ServiceWorker 接口继承它父类{{domxref("Worker")}}的属性.
代码段来自service worker registration-events sample (live demo). 这段代码监听了{{domxref("ServiceWorker.state")}} 的变化并且返回它的值.
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js', {
scope: './'
}).then(function (registration) {
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);
});
}
}).catch (function (error) {
// Something went wrong during registration. The service-worker.js file
// might be unavailable or contain a syntax error.
});
} else {
// The current browser doesn't support service workers.
}
| Specification | Status | Comment |
|---|---|---|
| {{SpecName('Service Workers', '#service-worker-obj', 'ServiceWorker')}} | {{Spec2('Service Workers')}} | Initial definition. |
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|---|---|---|---|---|---|
| Basic support | {{CompatChrome(40.0)}} | {{CompatGeckoDesktop("44.0")}}[1] | {{CompatNo}} | 24 | {{CompatNo}} |
| Feature | Android | Android Webview | Firefox Mobile (Gecko) | Firefox OS | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
|---|---|---|---|---|---|---|---|---|
| Basic support | {{CompatNo}} | {{CompatNo}} | {{CompatGeckoMobile("44.0")}} | {{ CompatVersionUnknown }} | {{CompatNo}} | {{CompatUnknown}} | {{CompatNo}} | {{CompatChrome(40.0)}} |
[1] Service workers (and Push) have been disabled in the Firefox 45 Extended Support Release (ESR.)