fix service worker

This commit is contained in:
jxxghp
2024-06-07 20:22:59 +08:00
parent 6620d1c8fe
commit aedb8bee9c
+33 -10
View File
@@ -15,10 +15,13 @@ registerRoute(new NavigationRoute(createHandlerBoundToURL('index.html'), { denyl
// 通知选项 // 通知选项
const options = { const options = {
icon: '/logo.png', icon: '/logo.png',
vibrate: [100, 50, 100],
actions: [{ action: 'close', title: '关闭' }],
} }
// 监听 push 事件,显示通知 // 监听 push 事件,显示通知
self.addEventListener('push', function (event) { self.addEventListener('push', function (event) {
console.log('notification push')
if (!event.data) { if (!event.data) {
return return
} }
@@ -34,18 +37,38 @@ self.addEventListener('push', function (event) {
} }
// 根据推送消息生成桌面通知并展现出来 // 根据推送消息生成桌面通知并展现出来
try { try {
let promise = self.registration.showNotification(payload.title, { const content = {
body: payload.body, body: payload.body || '',
icon: payload.icon ?? options.icon, icon: payload.icon || options.icon,
data: { vibrate: [100, 50, 100],
url: payload.url, data: { url: payload.url },
}, actions: options.actions,
}) }
event.waitUntil(promise) event.waitUntil(self.registration.showNotification(payload.title, content))
} catch (e) { } catch (e) {
console.error(e) console.error(e)
} }
}) })
self.skipWaiting() // 安装
clientsClaim() self.addEventListener('install', function (e) {
console.log('worker install')
self.skipWaiting()
})
// 激活
self.addEventListener('activate', function (e) {
console.log('worker activate')
e.waitUntil(self.clients.claim())
})
// 监听通知点击事件
self.addEventListener('notificationclick', function (event) {
console.log('notification click')
const info = event.notification
if (event.action === 'close') {
info.close()
} else if (info.data?.url) {
event.waitUntil(self.clients.openWindow(info.data?.url))
}
})