feat(service-worker): 兼容旧版前端监听逻辑

This commit is contained in:
PKC278
2026-01-06 14:10:57 +08:00
parent 38da061cf1
commit 689e58737b

View File

@@ -23,10 +23,27 @@ cleanupOutdatedCaches()
// 预缓存并路由
precacheAndRoute(self.__WB_MANIFEST)
// 变量记录是否为更新安装(兼容旧版前端监听逻辑)
let isUpdate = false
// 监听安装事件
self.addEventListener('install', () => {
// 强制跳过等待,自动激活
// 强制等待中的 Service Worker 立即激活
self.skipWaiting()
// 检查是否是更新(兼容旧版前端监听逻辑)
if (self.registration.active) {
isUpdate = true
// 通知客户端发现新版本
self.clients.matchAll({ includeUncontrolled: true, type: 'window' }).then(clients => {
clients.forEach(client => {
client.postMessage({
type: 'SW_VERSION_DETECTED',
version: CACHE_VERSION,
})
})
})
}
})
// 监听激活事件
@@ -38,6 +55,16 @@ self.addEventListener('activate', event => {
// 清理旧版本的运行时缓存
await cleanupRuntimeCaches(true)
// 如果是更新,则通知客户端刷新页面(兼容旧版前端监听逻辑)
if (isUpdate) {
const clients = await self.clients.matchAll({ type: 'window' })
clients.forEach(client => {
client.postMessage({
type: 'SW_RELOAD_PAGE',
})
})
}
})(),
)
})