49 lines
1.6 KiB
JavaScript
49 lines
1.6 KiB
JavaScript
/* Zovi service worker — Web Push display + Telegram-style tap-to-open.
|
|
Plain JS (runs in the SW global scope, outside the TS/React build). */
|
|
|
|
self.addEventListener('push', (event) => {
|
|
let payload = {};
|
|
try {
|
|
payload = event.data ? event.data.json() : {};
|
|
} catch {
|
|
payload = {};
|
|
}
|
|
const title = typeof payload.title === 'string' ? payload.title : 'New message';
|
|
const body = typeof payload.body === 'string' ? payload.body : '';
|
|
const conversationId = typeof payload.conversationId === 'string' ? payload.conversationId : '';
|
|
event.waitUntil(
|
|
self.registration.showNotification(title, {
|
|
body,
|
|
icon: '/icons/icon-192.png',
|
|
// Collapse multiple messages from the same chat into one notification.
|
|
tag: conversationId || undefined,
|
|
renotify: Boolean(conversationId),
|
|
data: { conversationId },
|
|
}),
|
|
);
|
|
});
|
|
|
|
self.addEventListener('notificationclick', (event) => {
|
|
event.notification.close();
|
|
const data = event.notification.data || {};
|
|
const conversationId = typeof data.conversationId === 'string' ? data.conversationId : '';
|
|
const url = conversationId ? `/?conversation=${conversationId}` : '/';
|
|
event.waitUntil(
|
|
(async () => {
|
|
const clientList = await self.clients.matchAll({
|
|
type: 'window',
|
|
includeUncontrolled: true,
|
|
});
|
|
for (const client of clientList) {
|
|
if ('focus' in client) {
|
|
await client.focus();
|
|
client.postMessage({ type: 'notification.open', conversationId });
|
|
return;
|
|
}
|
|
}
|
|
if (self.clients.openWindow) {
|
|
await self.clients.openWindow(url);
|
|
}
|
|
})(),
|
|
);
|
|
});
|