79 lines
1.7 KiB
JavaScript
79 lines
1.7 KiB
JavaScript
const CACHE_NAME = 'family-tree-v4'
|
|
|
|
// 安装 Service Worker
|
|
self.addEventListener('install', (event) => {
|
|
// 跳过等待,立即激活
|
|
self.skipWaiting()
|
|
})
|
|
|
|
// 激活 Service Worker
|
|
self.addEventListener('activate', (event) => {
|
|
event.waitUntil(
|
|
caches.keys().then((cacheNames) => {
|
|
return Promise.all(
|
|
cacheNames.map((cacheName) => {
|
|
if (cacheName !== CACHE_NAME) {
|
|
return caches.delete(cacheName)
|
|
}
|
|
})
|
|
)
|
|
}).then(() => {
|
|
// 立即控制所有页面
|
|
return self.clients.claim()
|
|
})
|
|
)
|
|
})
|
|
|
|
// 拦截请求 - 简化版,不缓存,只转发
|
|
self.addEventListener('fetch', (event) => {
|
|
// 只处理 GET 请求,其他请求直接转发
|
|
if (event.request.method !== 'GET') {
|
|
return
|
|
}
|
|
|
|
event.respondWith(
|
|
fetch(event.request).catch(() => {
|
|
// 网络失败时,尝试从缓存获取
|
|
return caches.match(event.request)
|
|
})
|
|
)
|
|
})
|
|
|
|
// 处理后台同步
|
|
self.addEventListener('sync', (event) => {
|
|
if (event.tag === 'sync-data') {
|
|
event.waitUntil(syncData())
|
|
}
|
|
})
|
|
|
|
async function syncData() {
|
|
// 这里可以实现数据同步逻辑
|
|
}
|
|
|
|
// 处理推送通知
|
|
self.addEventListener('push', (event) => {
|
|
const options = {
|
|
body: event.data ? event.data.text() : '您有新的家族更新',
|
|
icon: '/icon.svg',
|
|
badge: '/icon.svg',
|
|
vibrate: [200, 100, 200],
|
|
data: {
|
|
dateOfArrival: Date.now(),
|
|
primaryKey: 1
|
|
}
|
|
}
|
|
|
|
event.waitUntil(
|
|
self.registration.showNotification('家族树更新', options)
|
|
)
|
|
})
|
|
|
|
// 处理通知点击
|
|
self.addEventListener('notificationclick', (event) => {
|
|
event.notification.close()
|
|
|
|
event.waitUntil(
|
|
clients.openWindow('/')
|
|
)
|
|
})
|