0.0.0.4
This commit is contained in:
+116
@@ -0,0 +1,116 @@
|
||||
const CACHE_NAME = 'family-tree-v1'
|
||||
const urlsToCache = [
|
||||
'/',
|
||||
'/tree',
|
||||
'/members',
|
||||
'/timeline',
|
||||
'/settings',
|
||||
'/icon.svg',
|
||||
'/manifest.json'
|
||||
]
|
||||
|
||||
// 安装 Service Worker
|
||||
self.addEventListener('install', (event) => {
|
||||
event.waitUntil(
|
||||
caches.open(CACHE_NAME)
|
||||
.then((cache) => {
|
||||
console.log('Opened cache')
|
||||
return cache.addAll(urlsToCache)
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log('Cache installation failed:', error)
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
// 激活 Service Worker
|
||||
self.addEventListener('activate', (event) => {
|
||||
event.waitUntil(
|
||||
caches.keys().then((cacheNames) => {
|
||||
return Promise.all(
|
||||
cacheNames.map((cacheName) => {
|
||||
if (cacheName !== CACHE_NAME) {
|
||||
console.log('Deleting old cache:', cacheName)
|
||||
return caches.delete(cacheName)
|
||||
}
|
||||
})
|
||||
)
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
// 拦截请求
|
||||
self.addEventListener('fetch', (event) => {
|
||||
event.respondWith(
|
||||
caches.match(event.request)
|
||||
.then((response) => {
|
||||
// 缓存命中,返回缓存的资源
|
||||
if (response) {
|
||||
return response
|
||||
}
|
||||
|
||||
// 克隆请求
|
||||
const fetchRequest = event.request.clone()
|
||||
|
||||
return fetch(fetchRequest).then((response) => {
|
||||
// 检查是否是有效的响应
|
||||
if (!response || response.status !== 200 || response.type !== 'basic') {
|
||||
return response
|
||||
}
|
||||
|
||||
// 克隆响应
|
||||
const responseToCache = response.clone()
|
||||
|
||||
caches.open(CACHE_NAME)
|
||||
.then((cache) => {
|
||||
cache.put(event.request, responseToCache)
|
||||
})
|
||||
|
||||
return response
|
||||
})
|
||||
})
|
||||
.catch(() => {
|
||||
// 网络请求失败,返回离线页面
|
||||
return caches.match('/')
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
// 处理后台同步
|
||||
self.addEventListener('sync', (event) => {
|
||||
if (event.tag === 'sync-data') {
|
||||
event.waitUntil(syncData())
|
||||
}
|
||||
})
|
||||
|
||||
async function syncData() {
|
||||
// 这里可以实现数据同步逻辑
|
||||
console.log('Syncing data...')
|
||||
}
|
||||
|
||||
// 处理推送通知
|
||||
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('/')
|
||||
)
|
||||
})
|
||||
Reference in New Issue
Block a user