skipwaiting () при обновлении обнаружил, что моя страница попадает в бесконечный цикл - PullRequest
0 голосов
/ 09 июля 2020

служебный рабочий файл:

registration.onupdatefound = () => {
    const installingWorker = registration.installing;
    if (installingWorker == null) {
      return;
    }
    installingWorker.onstatechange = () => {
      if (installingWorker.state === 'installed') {
        if (navigator.serviceWorker.controller) {
          // At this point, the updated precached content has been fetched,
          // but the previous service worker will still serve the older
          // content until all client tabs are closed.
          console.log(
            'New content is available and will be used when all ' +
              'tabs for this page are closed.
          );

          // Execute callback
          registration.postMessage({action: 'skipWaiting'})
          if (config && config.onUpdate) {
            config.onUpdate(registration);
          }
        } else {
          // At this point, everything has been precached.
          // It's the perfect time to display a
          // "Content is cached for offline use." message.
          console.log('Content is cached for offline use.');

          // Execute callback
          if (config && config.onSuccess) {
            config.onSuccess(registration);
          }
        }
      }
    };
  };
}`
self.addEventListener('message', function(event) {
if (event.data.action === 'skipWaiting') {
  self.skipWaiting();
}

});

// прослушивание в приложении. js событие смены контроллера

// reload once when the new Service Worker starts activating
var refreshing;
navigator.serviceWorker.addEventListener('controllerchange',
function() {
if (refreshing) return;
refreshing = true;
window.location.reload();
 }
);

что на самом деле :

  1. Если он находит какое-либо обновление, отправляет postMessage как skipWating 2. После получения сообщения слушателем он вызывает skipWaiting () 3. затем вызывается событие controllerchange, при котором мы обновляем страницу.

Почему попадает в бесконечность l oop reload ()

1 Ответ

0 голосов
/ 09 июля 2020

Ваш первый бит кода, все под registration.onupdatefound, не должно быть в файле сервис-воркера. Он должен быть в контексте window вашего веб-приложения.

Бит, который должен быть в вашем служебном файле:

self.addEventListener('message', function(event) {
  if (event.data.action === 'skipWaiting') {
    self.skipWaiting();
  }
}

Есть документация для другого «рецепта», который выполняет это на https://developers.google.com/web/tools/workbox/guides/advanced-recipes#offer_a_page_reload_for_users. Он использует библиотеку workbox-window, чтобы немного упростить работу.

...