Service Worker文件未更新

时间:2018-05-31 07:01:29

标签: javascript service-worker

如果我的服务工作者文件(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或其他资产文件(例如),则不会建立更新。我不明白为什么:/

任何人都可以帮助我?

0 个答案:

没有答案