-
Notifications
You must be signed in to change notification settings - Fork 5
/
firebase-messaging-sw.js
94 lines (77 loc) · 2.68 KB
/
firebase-messaging-sw.js
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/* global importScripts, firebase */
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-messaging.js');
console.log('===========================================');
console.log('FIREBASE SERVICE WORKER LOADED');
console.log('===========================================');
firebase.initializeApp({
apiKey: '',
projectId: '',
messagingSenderId: '',
appId: '',
authDomain: '',
databaseURL: '',
storageBucket: '',
measurementId: '',
});
class CustomPushEvent extends Event {
constructor(data) {
super('push');
Object.assign(this, data);
this.custom = true;
}
}
/*
* Overrides push notification data, to avoid having 'notification' key and firebase blocking
* the message handler from being called
*/
self.addEventListener('push', (e) => {
// Skip if event is our own custom event
if (e.custom) return;
// Kep old event data to override
const oldData = e.data;
// Create a new event to dispatch, pull values from notification key and put it in data key,
// and then remove notification key
const newEvent = new CustomPushEvent({
data: {
ehheh: oldData.json(),
json() {
const newData = oldData.json();
newData.data = {
...newData.data,
...newData.notification,
};
delete newData.notification;
return newData;
},
},
waitUntil: e.waitUntil.bind(e),
});
// Stop event propagation
e.stopImmediatePropagation();
// Dispatch the new wrapped event
dispatchEvent(newEvent);
});
const messaging = firebase.messaging();
messaging.onBackgroundMessage((payload) => {
// console.log('[firebase-messaging-sw.js] Received background message ', payload);
const { title, body, icon, badge, ...restPayload } = payload.data;
const notificationOptions = {
body,
icon: icon || '/icons/firebase-logo.png', // path to your "fallback" firebase notification logo
badge: badge || '/icons/firebase-logo.png', // path to your "fallback" notification badge (Instead of the default bell)
data: restPayload,
};
return self.registration.showNotification(title, notificationOptions);
});
self.addEventListener('notificationclick', (event) => {
// console.log('[firebase-messaging-sw.js] notificationclick ', event);
// click_action described at https://github.com/BrunoS3D/firebase-messaging-sw.js#click-action
if (event.notification.data && event.notification.data.click_action) {
self.clients.openWindow(event.notification.data.click_action);
} else {
self.clients.openWindow(event.currentTarget.origin);
}
// close notification after click
event.notification.close();
});