Когда обновленный предварительно кэшированный контент будет извлечен, чтобы уведомление могло быть показано пользователю? - PullRequest
0 голосов
/ 08 октября 2019

Я пытаюсь показать пользователю уведомление при каждом обновлении предварительно кэшированного содержимого с помощью API уведомлений. В config.onUpdate(registration) я прошел registration. Всякий раз, когда регистрируется новый работник службы *, вызывается registration.onupdatefound, при этом проверяется, активирован ли serviceWorker или не использует navigator.serviceWorker.controller, если он активирован, тогда я показываю уведомление.

function registerValidSW(swUrl: string, config?: Config) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      Notification.requestPermission();
      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.PWA."
              );
              // Execute callback
              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);
              }
            }
          }
        };
      };
    })
    .catch(error => {
      console.error("Error during service worker registration:", error);
    });
}
let config ={
    onUpdate:(registration: ServiceWorkerRegistration)=>{
        if (Notification.permission == 'granted') {
            registration.showNotification('New content is available; please refresh.');
          }
    }
};

Ожидаемый вывод: - config.onUpdate() следует вызывать при наличии обновленного предварительно кэшированного содержимого.

Фактический вывод: - Когда я обновляю страницу, я получаю уведомление.

...