From 689e58737b38015f6ab0632d1f0b9420a97a117e Mon Sep 17 00:00:00 2001 From: PKC278 <52959804+PKC278@users.noreply.github.com> Date: Tue, 6 Jan 2026 14:10:57 +0800 Subject: [PATCH] =?UTF-8?q?feat(service-worker):=20=E5=85=BC=E5=AE=B9?= =?UTF-8?q?=E6=97=A7=E7=89=88=E5=89=8D=E7=AB=AF=E7=9B=91=E5=90=AC=E9=80=BB?= =?UTF-8?q?=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/service-worker.ts | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/service-worker.ts b/src/service-worker.ts index 8385dbc2..02fe04d1 100644 --- a/src/service-worker.ts +++ b/src/service-worker.ts @@ -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', + }) + }) + } })(), ) })