feat: 添加推送通知功能,支持订阅和发送通知
This commit is contained in:
@@ -107,17 +107,29 @@ self.addEventListener('sync', (event) => {
|
||||
// 推送通知
|
||||
self.addEventListener('push', (event) => {
|
||||
console.log('[Service Worker] 收到推送消息');
|
||||
let data = { title: '账单管理', body: '您有新的消息', url: '/', icon: '/icons/icon-192x192.png' };
|
||||
|
||||
if (event.data) {
|
||||
try {
|
||||
const json = event.data.json();
|
||||
data = { ...data, ...json };
|
||||
} catch (e) {
|
||||
data.body = event.data.text();
|
||||
}
|
||||
}
|
||||
|
||||
const options = {
|
||||
body: event.data ? event.data.text() : '您有新的账单消息',
|
||||
icon: '/icons/icon-192x192.png',
|
||||
body: data.body,
|
||||
icon: data.icon,
|
||||
badge: '/icons/icon-72x72.png',
|
||||
vibrate: [200, 100, 200],
|
||||
tag: 'emailbill-notification',
|
||||
requireInteraction: false
|
||||
requireInteraction: false,
|
||||
data: { url: data.url }
|
||||
};
|
||||
|
||||
event.waitUntil(
|
||||
self.registration.showNotification('账单管理', options)
|
||||
self.registration.showNotification(data.title, options)
|
||||
);
|
||||
});
|
||||
|
||||
@@ -125,8 +137,21 @@ self.addEventListener('push', (event) => {
|
||||
self.addEventListener('notificationclick', (event) => {
|
||||
console.log('[Service Worker] 通知被点击');
|
||||
event.notification.close();
|
||||
const urlToOpen = event.notification.data?.url || '/';
|
||||
event.waitUntil(
|
||||
clients.openWindow('/')
|
||||
clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windowClients) => {
|
||||
// 如果已经打开了该 URL,则聚焦
|
||||
for (let i = 0; i < windowClients.length; i++) {
|
||||
const client = windowClients[i];
|
||||
if (client.url === urlToOpen && 'focus' in client) {
|
||||
return client.focus();
|
||||
}
|
||||
}
|
||||
// 否则打开新窗口
|
||||
if (clients.openWindow) {
|
||||
return clients.openWindow(urlToOpen);
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user