ServiceWorker:statechange 事件
注意:此功能在Web Workers中可用。
当ServiceWorker.state
发生变化时,将触发statechange
事件。
语法
在诸如addEventListener()
之类的函数中使用事件名称,或者设置事件处理程序属性。
js
addEventListener("statechange", (event) => {});
onstatechange = (event) => {};
事件类型
一个通用的Event
。
示例
此代码片段取自service worker registration-events 示例(实时演示)。该代码监听ServiceWorker.state
的任何变化并返回其值。
js
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);
});
}
请注意,当statechange
触发时,Service Worker 的引用可能已更改。例如
js
navigator.serviceWorker.register("/sw.js").then((swr) => {
swr.installing.state = "installing";
swr.installing.onstatechange = () => {
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.
};
});
规范
规范 |
---|
Service Workers # dom-serviceworker-onstatechange |
浏览器兼容性
BCD 表格仅在启用 JavaScript 的浏览器中加载。