This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

ServiceWorker.onstatechange

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨апрель 2018 г.⁩.

Обработчик события, вызываемый при срабатывании события statechange; по сути, срабатывает при изменении ServiceWorker.state.

Синтаксис

ServiceWorker.onstatechange = function(statechangeevent) { ... }
ServiceWorker.addEventListener('statechange', function(statechangeevent) { ... } )

Примеры

Данный фрагмент кода из примера событий service worker (демо) возвращает состояние при каждом его изменении.

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);
  });
}

Обратите внимание, что при срабатывании statechange, ссылки на service worker могли измениться. Например:

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

Спецификации

Specification
Service Workers
# dom-serviceworker-onstatechange

Совместимость с браузерами