此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
ServiceWorker
Baseline
Widely available
*
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2018年4月.
* Some parts of this feature may have varying levels of support.
Service Worker API 的 ServiceWorker 接口提供了对 service worker 的引用。各个浏览上下文(例如页面、worker 等)可以与相同的 service worker 相关联,每个浏览上下文都可以通过唯一的 ServiceWorker 对象访问。
在 ServiceWorkerRegistration.active 属性和 ServiceWorkerContainer.controller 属性中有一个 ServiceWorker 对象——这是一个已激活并在控制页面的 service worker(service worker 成功注册,被控页面已经重新加载)。
ServiceWorker 接口被分配了一系列生命周期事件——install 和 activate——以及功能型的事件,包括 fetch。一个 ServiceWorker 对象有一个与之关联的 ServiceWorker.state,指示着它的生命周期。
实例属性
ServiceWorker 接口继承其父类 EventTarget 的属性。
ServiceWorker.scriptURL只读-
返回作为
ServiceWorkerRegistration一部分所定义的 ServiceWorker 序列化脚本 URL。这个 URL 必须和注册该ServiceWorker的文档处于同一域。 ServiceWorker.state只读-
返回 service worker 的状态。其值可能是如下之一:
installing、installed、activating、activated或redundant。
实例方法
ServiceWorker 接口继承其父类 EventTarget 的方法。
事件
ServiceWorker.onstatechange只读-
每当
ServiceWorker.state发生改变时,都会触发。
示例
代码段来自 service worker registration-events sample(在线演示)。这段代码监听了 ServiceWorker.state 的变化并且返回它的值。
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("service-worker.js", {
scope: "./",
})
.then((registration) => {
let 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", (e) => {
// logState(e.target.state);
});
}
})
.catch((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.
// Perhaps it is too old or we are not in a Secure Context.
}
规范
| Specification |
|---|
| Service Workers> # serviceworker-interface> |
浏览器兼容性
Loading...