-
Notifications
You must be signed in to change notification settings - Fork 0
/
firebase-messaging-sw.js
85 lines (76 loc) · 2.61 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
importScripts(
"https://www.gstatic.com/firebasejs/9.0.0/firebase-app-compat.js"
);
importScripts(
"https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging-compat.js"
);
// Initialize the Firebase app in the service worker by passing in the messagingSenderId.
firebase.initializeApp({
apiKey: "AIzaSyBNlZDqGxMyI83DbW4hY0qd4KAJA3ynW2Q",
authDomain: "waiter-dev-ca07d.firebaseapp.com",
projectId: "waiter-dev-ca07d",
storageBucket: "waiter-dev-ca07d.appspot.com",
messagingSenderId: "699328756162",
appId: "1:699328756162:web:f11e002f4f3dd23bd23e5b",
measurementId: "G-F4YF1WECQR",
});
// Retrieve an instance of Firebase Messaging so that it can handle background messages.
const messaging = firebase.messaging();
messaging.onBackgroundMessage((payload) => {
console.log(
"[firebase-messaging-sw.js] Received background message ",
payload
);
// Customize notification here
const notificationTitle = payload.notification.title || "New Notification";
const notificationOptions = {
body: payload.notification.body || "You have a new message",
// icon: "/path/to/your/icon.png", // Replace with the path to your app icon
// badge: "/path/to/your/badge.png", // Replace with the path to your badge icon
tag: "new-message", // Unique identifier for the notification
data: payload.data, // Include any additional data from the payload
requireInteraction: true, // Keep the notification visible until the user interacts with it
actions: [
{
action: "open",
title: "Open App",
},
{
action: "close",
title: "Dismiss",
},
],
};
console.log(
"Attempting to show notification:",
notificationTitle,
notificationOptions
);
return self.registration
.showNotification(notificationTitle, notificationOptions)
.then(() => {
console.log("Notification shown successfully");
})
.catch((error) => {
console.error("Error showing notification:", error);
console.error("Error name:", error.name);
console.error("Error message:", error.message);
console.error("Error stack:", error.stack);
});
});
self.addEventListener("notificationclick", (event) => {
event.notification.close();
if (event.action === "open") {
clients.openWindow("/"); // Adjust the URL to where you want to navigate
} else if (event.action === "close") {
// Handle dismiss action if needed
}
event.waitUntil(
clients.matchAll({ type: "window" }).then((clientList) => {
if (clientList.length > 0) {
return clientList[0].focus();
}
return clients.openWindow("/");
})
);
});