41 lines
1.2 KiB
JavaScript
41 lines
1.2 KiB
JavaScript
// This file is based on the one found in the laravel-notification-channels/webpush package.
|
|
|
|
// We need this to get the VAPID_PUBLIC_KEY from the .env file
|
|
const vapidPublicKey = import.meta.env.VITE_VAPID_PUBLIC_KEY;
|
|
|
|
self.addEventListener('push', (event) => {
|
|
const payload = event.data ? event.data.json() : {};
|
|
|
|
const options = {
|
|
body: payload.body,
|
|
icon: payload.icon,
|
|
badge: payload.badge,
|
|
data: {
|
|
url: payload.url,
|
|
},
|
|
};
|
|
|
|
event.waitUntil(self.registration.showNotification(payload.title, options));
|
|
});
|
|
|
|
self.addEventListener('notificationclick', (event) => {
|
|
event.notification.close();
|
|
|
|
event.waitUntil(
|
|
clients.openWindow(event.notification.data.url)
|
|
);
|
|
});
|
|
|
|
if (vapidPublicKey) {
|
|
self.addEventListener('load', async () => {
|
|
if ('serviceWorker' in navigator) {
|
|
try {
|
|
const registration = await navigator.serviceWorker.register('/sw.js');
|
|
console.log('Service worker registered.', registration);
|
|
} catch (error) {
|
|
console.error('Error registering service worker:', error);
|
|
}
|
|
}
|
|
});
|
|
}
|