const CACHE_NAME = 'cyrene-v1'; const ASSETS_TO_CACHE = [ '/', '/index.html', ]; // Install: 缓存核心资源 self.addEventListener('install', (event) => { event.waitUntil( caches.open(CACHE_NAME).then((cache) => { return cache.addAll(ASSETS_TO_CACHE); }) ); self.skipWaiting(); }); // Activate: 清理旧缓存 self.addEventListener('activate', (event) => { event.waitUntil( caches.keys().then((keys) => { return Promise.all( keys.filter(key => key !== CACHE_NAME).map(key => caches.delete(key)) ); }) ); self.clients.claim(); }); // Fetch: 缓存优先策略(对 API 请求使用网络优先) self.addEventListener('fetch', (event) => { const url = new URL(event.request.url); // API 请求:网络优先,失败时返回离线 JSON if (url.pathname.startsWith('/api/')) { event.respondWith(networkFirst(event.request)); } else if (url.pathname.startsWith('/ws')) { // WebSocket 连接不缓存 event.respondWith(fetch(event.request)); } else { // 静态资源:缓存优先 event.respondWith(cacheFirst(event.request)); } }); async function cacheFirst(request) { const cached = await caches.match(request); if (cached) return cached; try { const response = await fetch(request); if (response.ok) { const cache = await caches.open(CACHE_NAME); cache.put(request, response.clone()); } return response; } catch (e) { // 返回离线页面(HTML 请求) if (request.headers.get('Accept')?.includes('text/html')) { return caches.match('/offline.html'); } throw e; } } async function networkFirst(request) { try { const response = await fetch(request); const cache = await caches.open(CACHE_NAME); cache.put(request, response.clone()); return response; } catch (e) { const cached = await caches.match(request); if (cached) return cached; return new Response(JSON.stringify({ error: '离线状态,请检查网络连接' }), { status: 503, headers: { 'Content-Type': 'application/json' } }); } } // Push 通知 self.addEventListener('push', (event) => { const data = event.data?.json() || { title: 'Cyrene', body: '新消息' }; event.waitUntil( self.registration.showNotification(data.title, { body: data.body, icon: '/images/Cyrene_Avatar/2nd_Form/Cyrene-2F-N-Happy-1.png', badge: '/images/Cyrene_Avatar/2nd_Form/Cyrene-2F-N-Happy-1.png', data: data.data || {}, }) ); }); self.addEventListener('notificationclick', (event) => { event.notification.close(); const sessionId = event.notification.data?.session_id; const targetUrl = sessionId ? `/#/session/${sessionId}` : '/'; event.waitUntil( clients.matchAll({ type: 'window' }).then((clientList) => { for (const client of clientList) { if (client.url.includes(targetUrl) && 'focus' in client) { return client.focus(); } } if (clients.openWindow) return clients.openWindow(targetUrl); }) ); });