feat: 添加推送通知功能,支持订阅和发送通知
All checks were successful
Docker Build & Deploy / Build Docker Image (push) Successful in 40s
Docker Build & Deploy / Deploy to Production (push) Successful in 8s

This commit is contained in:
2026-01-02 12:25:44 +08:00
parent a055e43451
commit e250a7df2f
17 changed files with 382 additions and 13 deletions

View File

@@ -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);
}
})
);
});