Файл Service Worker не обновляется - PullRequest
0 голосов
/ 31 мая 2018

Я хотел бы добавить уведомление, если мой файл рабочего сервиса (sw.js) отредактирован.Итак, я добавил updatefound событие, но я никогда не входил.

Вы можете увидеть мой код:

if ('serviceWorker' in navigator && 'PushManager' in window) {
  console.log('Service Worker and Push is supported');

  navigator.serviceWorker
    .register("/sw.js")
    .then(registration => {
      console.log("[PWA] Service Worker Install successful");

      registration.addEventListener("updatefound", () => {
        console.log('[PWA] Update found');

        const newWorker = registration.installing;

        newWorker.addEventListener("statechange", () => {

          console.log("[PWA] State :", newWorker.state);

          switch (newWorker.state) {
            case 'installed':

              if (navigator.serviceWorker.controller) {
                const updateIsAvailable = confirm('New Service Worker is available, refrech window ?');

                if (updateIsAvailable) {
                  window.location.reload();
                }
              }
              break;
          }
        });
      });
    })
    .catch(error => console.log(`[PWA] Error during service worker registration : ${error}`));
} else {
  console.log('Service Worker or Push is not supported');
}

И в моем sw.js событие получения:

self.addEventListener("fetch", event => {
  /**
   * Update cache
   * @param {string} request
   */
  const updateCache = request => {
    return caches
      .open(CACHE_NAME)
      .then(cache => {
        return fetch(request)
          .then(response => {
            console.log(`[PWA] add page to offline ${response.url}`);
            return cache.put(request, response);
          })
          .catch(error => console.log(error));
      })
      .catch(error => console.log(error));
  };

  event.waitUntil(updateCache(event.request));

  event.respondWith(
    fetch(event.request).catch(error => {
      console.log(
        `[PWA] Network request Failed. Serving content from cache: ${error}`
      );

      // Check to see if you have it in the cache
      // Return response
      // If not in the cache, then return error page
      return caches
        .open(CACHE_NAME)
        .then(cache => {
          return cache.match(event.request).then(matching => {
            const report =
              !matching || matching.status == 404
                ? Promise.reject("no-match")
                : matching;
            return report;
          });
        })
        .catch(error => console.log(error));
    })
  );
});

Если я отредактирую свой файл sw.js или другой ресурс (например), обновление не будет найдено.Я не понимаю, почему: /

Кто-нибудь может мне помочь?

...