68 lines
1.7 KiB
JavaScript
68 lines
1.7 KiB
JavaScript
// Service Worker para Push Notifications
|
|
self.addEventListener('install', (event) => {
|
|
console.log('Service Worker instalado');
|
|
self.skipWaiting();
|
|
});
|
|
|
|
self.addEventListener('activate', (event) => {
|
|
console.log('Service Worker ativado');
|
|
event.waitUntil(self.clients.claim());
|
|
});
|
|
|
|
// Escutar push notifications
|
|
self.addEventListener('push', (event) => {
|
|
console.log('Push notification recebida:', event);
|
|
|
|
let data = {};
|
|
if (event.data) {
|
|
try {
|
|
data = event.data.json();
|
|
} catch (e) {
|
|
data = { title: 'Nova notificação', body: event.data.text() };
|
|
}
|
|
}
|
|
|
|
const title = data.title || 'SGSE';
|
|
const options = {
|
|
body: data.body || 'Você tem uma nova notificação',
|
|
icon: data.icon || '/favicon.png',
|
|
badge: data.badge || '/favicon.png',
|
|
tag: data.tag || 'default',
|
|
requireInteraction: data.requireInteraction || false,
|
|
data: data.data || {}
|
|
};
|
|
|
|
event.waitUntil(self.registration.showNotification(title, options));
|
|
});
|
|
|
|
// Escutar cliques em notificações
|
|
self.addEventListener('notificationclick', (event) => {
|
|
console.log('Notificação clicada:', event);
|
|
|
|
event.notification.close();
|
|
|
|
// Abrir/focar na aplicação
|
|
event.waitUntil(
|
|
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
|
|
// Se há um cliente aberto, focar nele
|
|
for (const client of clientList) {
|
|
if (client.url && 'focus' in client) {
|
|
return client.focus();
|
|
}
|
|
}
|
|
|
|
// Se não há cliente aberto, abrir nova janela
|
|
if (self.clients.openWindow) {
|
|
const data = event.notification.data;
|
|
let url = '/';
|
|
|
|
if (data?.conversaId) {
|
|
url = `/chat?conversa=${data.conversaId}`;
|
|
}
|
|
|
|
return self.clients.openWindow(url);
|
|
}
|
|
})
|
|
);
|
|
});
|