tasq/web/firebase-messaging-sw.js

79 lines
2.6 KiB
JavaScript

importScripts('https://www.gstatic.com/firebasejs/9.22.2/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.22.2/firebase-messaging-compat.js');
// This file must be served with "Content-Type: application/javascript" and
// placed at the root of the `web/` build output. Flutter web does not copy it
// automatically, so ensure you add a manual copy step to your build script or
// include it in `web/` before building.
firebase.initializeApp({
// values must match `firebase_options.dart` generated by `flutterfire`
apiKey: 'AIzaSyBKGSaHYiqpZvbEgsvJJY45soiIkV6MV3M',
appId: '1:173359574734:web:f894a6b43a443e902baa9f',
messagingSenderId: '173359574734',
projectId: 'tasq-17fb3',
authDomain: 'tasq-17fb3.firebaseapp.com',
storageBucket: 'tasq-17fb3.firebasestorage.app',
});
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function(payload) {
const notificationTitle = payload.notification?.title
|| payload.data?.title
|| 'TasQ Notification';
const notificationBody = payload.notification?.body
|| payload.data?.body
|| '';
const notificationOptions = {
body: notificationBody,
icon: '/icons/Icon-192.png',
badge: '/icons/Icon-192.png',
data: payload.data,
// tag deduplicates: same notification_id won't stack
tag: payload.data?.notification_id || payload.messageId || 'tasq',
renotify: true,
};
return self.registration.showNotification(notificationTitle, notificationOptions);
});
// Handle notification click — focus the PWA window and navigate to the
// relevant task / ticket route based on the data payload.
self.addEventListener('notificationclick', function(event) {
event.notification.close();
const data = event.notification.data || {};
const navigateTo = data.navigate_to || data.route;
const taskId = data.task_id || data.taskId;
const ticketId = data.ticket_id || data.ticketId;
let targetPath = '/';
if (navigateTo && navigateTo !== '/') {
targetPath = navigateTo;
} else if (taskId) {
targetPath = '/tasks/' + taskId;
} else if (ticketId) {
targetPath = '/tickets/' + ticketId;
}
event.waitUntil(
clients
.matchAll({ type: 'window', includeUncontrolled: true })
.then(function(clientList) {
// If the app is already open, navigate it and bring it to front
for (const client of clientList) {
if ('navigate' in client) {
client.navigate(targetPath);
return client.focus();
}
}
// Otherwise open a new window
if (clients.openWindow) {
return clients.openWindow(targetPath);
}
})
);
});