--- 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. |