-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathnotification-sw.js
56 lines (47 loc) · 1.41 KB
/
notification-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
self.addEventListener("install", () => {
console.info("service worker installed.");
});
const sendDeliveryReportAction = () => {
console.log("Web push delivered.");
};
self.addEventListener("push", function (event) {
if (!event.data) {
return;
}
const payload = event.data.json();
const { body, icon, image, badge, url, title } = payload;
const notificationTitle = title ?? "Unknown title";
const notificationOptions = {
body,
icon,
image,
data: {
url,
},
badge,
};
event.waitUntil(
self.registration.showNotification(notificationTitle, notificationOptions).then(() => {
sendDeliveryReportAction();
})
);
});
self.addEventListener("notificationclick", function (event) {
console.log("Notification clicked.");
event.notification.close();
event.waitUntil(
clients.matchAll({ type: "window", includeUncontrolled: true }).then((clientList) => {
const url = event.notification.data.url;
if (!url) return;
for (const client of clientList) {
if (client.url === url && "focus" in client) {
return client.focus();
}
}
if (clients.openWindow) {
console.log("Opening window.");
return clients.openWindow(url);
}
})
);
});