-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfirebase-messaging-sw.ts
39 lines (33 loc) · 1.08 KB
/
firebase-messaging-sw.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// / <reference lib="WebWorker" />
// @ts-ignore
// eslint-disable-next-line no-undef
declare let self: ServiceWorkerGlobalScope;
import { initializeApp } from 'firebase/app';
import { getMessaging, MessagePayload, onMessage } from 'firebase/messaging';
const buildNotification = (payload: MessagePayload) => {
const { data } = payload;
return {
...{
title: 'Notification',
},
...data,
...{
data: {
click_action: data.click_action,
},
},
};
};
fetch('/__/firebase/init.json').then(async (response) => {
const app = initializeApp(await response.json());
const messaging = getMessaging(app);
onMessage(messaging, (payload) => {
const notification = buildNotification(payload);
return self.registration.showNotification(notification.title, notification);
});
});
self.addEventListener('notificationclick', (event) => {
const isPath = event.notification?.data?.click_action?.startsWith('/');
const url = `${isPath ? self.origin : ''}${event.notification.data.click_action}`;
event.waitUntil(self.clients.openWindow(url));
});