diff --git a/Web/public/service-worker.js b/Web/public/service-worker.js index e4b575c..6781abe 100644 --- a/Web/public/service-worker.js +++ b/Web/public/service-worker.js @@ -1,4 +1,5 @@ -const CACHE_NAME = 'emailbill-v1'; +const VERSION = '1.0.0'; // Build Time: 2026-01-07 15:59:36 +const CACHE_NAME = `emailbill-${VERSION}`; const urlsToCache = [ '/', '/index.html', @@ -57,11 +58,13 @@ self.addEventListener('fetch', (event) => { event.respondWith( fetch(request) .then((response) => { - // 克隆响应以便缓存 - const responseClone = response.clone(); - caches.open(CACHE_NAME).then((cache) => { - cache.put(request, responseClone); - }); + // 只针对成功的GET请求进行缓存 + if (request.method === 'GET' && response.status === 200) { + const responseClone = response.clone(); + caches.open(CACHE_NAME).then((cache) => { + cache.put(request, responseClone); + }); + } return response; }) .catch(() => { @@ -72,7 +75,25 @@ self.addEventListener('fetch', (event) => { return; } - // 静态资源使用缓存优先策略 + // 页面请求使用网络优先策略,确保能获取到最新的 index.html + if (request.mode === 'navigate') { + event.respondWith( + fetch(request) + .then((response) => { + const responseClone = response.clone(); + caches.open(CACHE_NAME).then((cache) => { + cache.put(request, responseClone); + }); + return response; + }) + .catch(() => { + return caches.match('/index.html') || caches.match(request); + }) + ); + return; + } + + // 其他静态资源使用缓存优先策略 event.respondWith( caches.match(request) .then((response) => { diff --git a/Web/src/registerServiceWorker.js b/Web/src/registerServiceWorker.js index f46bab9..b0d4608 100644 --- a/Web/src/registerServiceWorker.js +++ b/Web/src/registerServiceWorker.js @@ -20,6 +20,12 @@ export function register() { swRegistration = registration; console.log('[SW] Service Worker 注册成功:', registration.scope); + // 如果已经有等待中的更新 + if (registration.waiting) { + console.log('[SW] 发现未处理的新版本'); + needRefresh.value = true; + } + // 检查更新 registration.addEventListener('updatefound', () => { const newWorker = registration.installing; diff --git a/Web/vite.config.js b/Web/vite.config.js index 6495fef..e110e3f 100644 --- a/Web/vite.config.js +++ b/Web/vite.config.js @@ -1,4 +1,6 @@ import { fileURLToPath, URL } from 'node:url' +import { writeFileSync, readFileSync, existsSync } from 'node:fs' +import { resolve } from 'node:path' import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' @@ -9,6 +11,20 @@ export default defineConfig({ plugins: [ vue(), vueDevTools(), + { + name: 'update-sw-version', + apply: 'build', + closeBundle() { + const swPath = resolve(fileURLToPath(new URL('.', import.meta.url)), 'dist/service-worker.js') + if (existsSync(swPath)) { + let content = readFileSync(swPath, 'utf8') + const timestamp = new Date().toISOString() + content = content.replace(/const VERSION = '.*';/, `const VERSION = '${timestamp}';`) + writeFileSync(swPath, content) + console.log(`[SW Update] Version updated to ${timestamp}`) + } + } + } ], resolve: { alias: {