如果缓存名称不同,请手动更新servceworker缓存

时间:2018-03-14 08:50:03

标签: javascript service-worker

所以我有一个PWA,我想添加一个按钮,让用户知道有一个新版本可用,以便他们可以更新所有文件,如果他们有互联网连接。每次运行gulp build时,它都会为服务工作者缓存名称添加时间戳,因此它总是新鲜的,但它不会更新缓存的文件。

这是gulp任务:

gulp.task('serviceWorkerCache', function(){
    gulp.src(['dist/serviceworker.js'])
        .pipe(replace(/(dobrywebdev-\d{0,13})/g, function(match, p1, offset, string) {
            var currentDate = Date.now();
            return 'dobrywebdev-' + currentDate;
        }))
    .pipe(gulp.dest('dist'));
});

整个service-worker.js文件:

const CACHE_NAME = "dobrywebdev-1521013165219"; // that number is the timestamp that changes
const URLS_TO_CACHE  = [
    "/",
    "/index.html",
    "/errors/404.html",
    "/manifest.json",
    "https://fonts.googleapis.com/css?family=Poppins:400,700&subset=latin-ext",
    "/css/main.min.css",
    "/js/main.min.js",
    "/fonts/devicons.eot",
    "/fonts/devicons.svg",
    "/fonts/devicons.ttf",
    "/fonts/devicons.woff",
    "/font/fontello.eot",
    "/font/fontello.svg",
    "/font/fontello.ttf",
    "/font/fontello.woff",
    "/font/fontello.woff2",
    "/json/content-eng.json",
    "/json/content-pl.json",
    "/img/playground.png",
    "/img/agency.png",
    "/img/cv.png",
    "/img/dobrywebdev.png",
    "/img/dobrywebdevfb.png",
    "/img/form.png",
    "/img/interior.png",
    "/img/interior1.png",
    "/img/logo-dark.png",
    "/img/logo-light.png",
    "/img/simpleweather.png",
    "/img/sleszynski.png",
    "/img/todo.png",
    "/img/webdev37.png",
    "/android-chrome-36x36.png",
    "/android-chrome-48x48.png",
    "/android-chrome-72x72.png",
    "/android-chrome-96x96.png",
    "/android-chrome-144x144.png",
    "/android-chrome-192x192.png",
    "/android-chrome-256x256.png",
    "/android-chrome-512x512.png",
    "/apple-touch-icon.png",
    "/apple-touch-icon-60x60.png",
    "/apple-touch-icon-76x76.png",
    "/apple-touch-icon-120x120.png",
    "/apple-touch-icon-152x152.png",
    "/apple-touch-icon-180x180.png",
    "/browserconfig.xml",
    "/favicon-16x16.png",
    "/favicon-32x32.png",
    "/mstile-150x150.png",
    "/safari-pinned-tab.svg"
];

self.addEventListener('install', function(event) {
    event.waitUntil(
        caches.open(CACHE_NAME)
        .then(function(cache) {
            console.log('Opened cache');
            return cache.addAll(URLS_TO_CACHE);
        }).catch(function(error) {
            console.log(error);
        })
    );
});

self.addEventListener("activate", event => {
    event.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames
          .filter(name => name.includes("dobrywebdev") && name !== CACHE_NAME)
          .map(name => caches.delete(name))
      )
    }).then(() => self.clients.claim())
  );
});

self.addEventListener('fetch', function(event) {
    event.respondWith(
        caches.match(event.request)
            .then(function(response) {
            if (response) {
                return response;
            }
            var fetchRequest = event.request.clone();
            return fetch(fetchRequest).then(
            function(response) {
                if(!response || response.status !== 200 || response.type !== 'basic') {
                    return response;
            }
            var responseToCache = response.clone();
            caches.open(CACHE_NAME)
                .then(function(cache) {
                    cache.put(event.request, responseToCache);
                    });
                    return response;
                }
            );
        })
    );
});

在main.js注册:

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/serviceworker.js').then(function(registration) {
      console.log('Service worker registration done, scope is:', registration.scope);
    }).catch(function(err) {
      console.log('ServiceWorker registration failed: ', err);
    });
}

所以基本上我想检查serviceworker.js中的CACHE_NAME是否与实际浏览器缓存中的class Chat extends React.Component { constructor () { super(); this.params = BotChat.queryParams(location.search); this.initChatDebug(); } initChatDebug () { window.botchatDebug = this.params.debug && this.params.debug === 'true'; } } 不同,并显示一个按钮/弹出窗口,其中包含更新应用程序的选项。然后该按钮应删除缓存,取消注册serviceworker,注册一个新缓存并将文件添加到缓存。根据我的阅读,服务人员无法做任何与DOM相关的事情,所以我必须通过main.js来完成。我该怎么做?

1 个答案:

答案 0 :(得分:2)

我不认为你需要这样说实话,因为每次更新服务工作者的版本时,浏览器会自动删除旧版本。我认为您需要在服务工作者的某处包含这段代码:

self.addEventListener('activate', function (event) {
  console.log('[Service Worker] Activating Service Worker ....', event);
  event.waitUntil(
    caches.keys()
      .then(function (keyList) {
        return Promise.all(keyList.map(function (key) {
          if (key !== CACHE_STATIC_NAME && key !== CACHE_DYNAMIC_NAME) {
            console.log('[Service Worker] Removing old cache.', key);
            return caches.delete(key);
          }
        }));
      })
  );
  return self.clients.claim();
});

这将删除旧缓存并更新服务工作者