This repository has been archived by the owner on Sep 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
/
service-worker.js
66 lines (54 loc) · 2.07 KB
/
service-worker.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
'use strict';
importScripts('./js/util.js');
self.addEventListener('install', function (event) {
self.skipWaiting();
});
self.addEventListener('activate', function (event) {
event.waitUntil(clients.claim());
});
// Respond to a server push with a user notification
self.addEventListener('push', function (event) {
if (event.data) {
const { title, lang = 'en', body, tag, timestamp, requireInteraction, actions, image } = event.data.json();
const promiseChain = self.registration.showNotification(title, {
lang,
body,
requireInteraction,
tag: tag || undefined,
timestamp: timestamp ? Date.parse(timestamp) : undefined,
actions: actions || undefined,
image: image || undefined,
badge: '/images/favicon.png',
icon: '/images/toast-image.jpg'
});
// Ensure the toast notification is displayed before exiting this function
event.waitUntil(promiseChain);
}
});
self.addEventListener('notificationclick', function (event) {
event.notification.close();
event.waitUntil(
clients.matchAll({ type: 'window', includeUncontrolled: true })
.then(function (clientList) {
if (clientList.length > 0) {
let client = clientList[0];
for (let i = 0; i < clientList.length; i++) {
if (clientList[i].focused) {
client = clientList[i];
}
}
return client.focus();
}
return clients.openWindow('/');
})
);
});
self.addEventListener('pushsubscriptionchange', function (event) {
event.waitUntil(
Promise.all([
Promise.resolve(event.oldSubscription ? deleteSubscription(event.oldSubscription) : true),
Promise.resolve(event.newSubscription ? event.newSubscription : subscribePush(registration))
.then(function (sub) { return saveSubscription(sub); })
])
);
});