Workbox 在新版本上更新缓存

Ker*_*mit 5 javascript caching service-worker workbox

我已经实现了 Workbox 来使用 webpack 生成我的 Service Worker。这工作得很好 - 我可以确认revision运行时生成的服务工作线程中已更新yarn run generate-sw(package.json "generate-sw": "workbox inject:manifest":)。

问题是 - 我注意到我的客户在新版本发布后没有更新缓存。即使在更新服务工作线程数天后,我的客户端仍在缓存旧代码,而新代码仅在多次刷新和/或取消注册服务工作线程后才会缓存。对于每个版本const CACHE_DYNAMIC_NAME = 'dynamic-v1.1.0'都会更新。

如何确保客户端在新版本发布后立即更新缓存?

serviceWorker-base.js

importScripts('workbox-sw.prod.v2.1.3.js')

const CACHE_DYNAMIC_NAME = 'dynamic-v1.1.0'
const workboxSW = new self.WorkboxSW()

// Cache then network for fonts
workboxSW.router.registerRoute(
  /.*(?:googleapis)\.com.*$/, 
  workboxSW.strategies.staleWhileRevalidate({
    cacheName: 'google-font',
    cacheExpiration: {
      maxEntries: 1, 
      maxAgeSeconds: 60 * 60 * 24 * 28
    }
  })
)

// Cache then network for css
workboxSW.router.registerRoute(
  '/dist/main.css',
  workboxSW.strategies.staleWhileRevalidate({
    cacheName: 'css'
  })
)

// Cache then network for avatars
workboxSW.router.registerRoute(
  '/img/avatars/:avatar-image', 
  workboxSW.strategies.staleWhileRevalidate({
    cacheName: 'images-avatars'
  })
)

// Cache then network for images
workboxSW.router.registerRoute(
  '/img/:image', 
  workboxSW.strategies.staleWhileRevalidate({
    cacheName: 'images'
  })
)

// Cache then network for icons
workboxSW.router.registerRoute(
  '/img/icons/:image', 
  workboxSW.strategies.staleWhileRevalidate({
    cacheName: 'images-icons'
  })
)

// Fallback page for html files
workboxSW.router.registerRoute(
  (routeData)=>{
    // routeData.url
    return (routeData.event.request.headers.get('accept').includes('text/html'))
  }, 
  (args) => {
    return caches.match(args.event.request)
    .then((response) => {
      if (response) {
        return response
      }else{
        return fetch(args.event.request)
        .then((res) => {
          return caches.open(CACHE_DYNAMIC_NAME)
          .then((cache) => {
            cache.put(args.event.request.url, res.clone())
            return res
          })
        })
        .catch((err) => {
          return caches.match('/offline.html')
          .then((res) => { return res })
        })
      }
    })
  }
)

workboxSW.precache([])

// Own vanilla service worker code
self.addEventListener('notificationclick', function (event){
  let notification = event.notification
  let action = event.action
  console.log(notification)

  if (action === 'confirm') {
    console.log('Confirm was chosen')
    notification.close()
  } else {
    const urlToOpen = new URL(notification.data.url, self.location.origin).href;

    const promiseChain = clients.matchAll({ type: 'window', includeUncontrolled: true })
    .then((windowClients) => {
      let matchingClient = null;
      let matchingUrl = false;
      for (let i=0; i < windowClients.length; i++){
        const windowClient = windowClients[i];

        if (windowClient.visibilityState === 'visible'){
          matchingClient = windowClient;
          matchingUrl = (windowClient.url === urlToOpen);
          break;
        }
      }

      if (matchingClient){
        if(!matchingUrl){ matchingClient.navigate(urlToOpen); }
        matchingClient.focus();
      } else {
        clients.openWindow(urlToOpen);
      }

      notification.close();
    });

    event.waitUntil(promiseChain);
  }
})

self.addEventListener('notificationclose', (event) => {
  // Great place to send back statistical data to figure out why user did not interact
  console.log('Notification was closed', event)
})

self.addEventListener('push', function (event){
  console.log('Push Notification received', event)

  // Default values
  const defaultData = {title: 'New!', content: 'Something new happened!', openUrl: '/'}
  const data = (event.data) ? JSON.parse(event.data.text()) : defaultData

  var options = {
    body: data.content,
    icon: '/images/icons/manifest-icon-512.png', 
    badge: '/images/icons/badge128.png', 
    data: {
      url: data.openUrl
    }
  }

  console.log('options', options)

  event.waitUntil(
    self.registration.showNotification(data.title, options)
  )
})
Run Code Online (Sandbox Code Playgroud)

我应该手动删除缓存还是 Workbox 应该为我删除缓存?

caches.keys().then(cacheNames => {
  cacheNames.forEach(cacheName => {
    caches.delete(cacheName);
  });
});
Run Code Online (Sandbox Code Playgroud)

亲切的问候/K

Gio*_*dze 3

我认为您的问题与以下事实有关:当您对应用程序进行更新并部署时,会安装新的服务工作人员,但不会激活。这解释了为什么会发生这种情况。

原因是registerRoute函数还注册了fetch侦听器,但是在新的服务工作线程激活之前,这些获取侦听器不会被调用。另外,你的问题的答案:不,你不需要自己删除缓存。Workbox 会处理这些。

让我了解更多细节。当您部署新代码时,如果用户关闭网站的所有选项卡并随后打开一个新选项卡,它会在 2 次刷新后开始工作吗?如果是这样,那么它应该是这样工作的。在您提供更多详细信息后,我将更新我的答案。

我建议您阅读以下内容:https://redfin.engineering/how-to-fix-the-refresh-button-when-using-service-workers-a8e27af6df68并遵循第三种方法。