-
Notifications
You must be signed in to change notification settings - Fork 1
/
sw.js
76 lines (65 loc) · 1.87 KB
/
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
self.addEventListener('install', (event) => {
console.log('SW', 'install', location.protocol, event);
// Don't block activation
if (self.skipWaiting) {
self.skipWaiting();
}
});
self.addEventListener('activate', (event) => {
console.log('SW', 'activate', OFFLINE_VERSION, event);
if (self.clients && 'claim' in self.clients) {
self.clients.claim();
}
});
self.addEventListener('controllerchange', () => {
if (self.skipWaiting) {
self.skipWaiting();
}
});
// ExtendableMessageEvent
self.addEventListener('message', (event) => {
console.log('SW', 'message', event.origin, JSON.stringify(event.data));
});
// Focus a window and send a message
function sendWindowMessage(windowMessage) {
return self.clients.matchAll({
type: 'window',
includeUncontrolled: true,
})
.then((windowClients) => {
if (windowClients.length) {
if ('focus' in windowClients[0]) {
return windowClients[0].focus();
}
windowClients[0].postMessage(windowMessage);
}
});
}
function getNotificationMessage(notif) {
return JSON.stringify({
type: notif.data.event_type,
tag: notif.tag,
timestamp: notif.timestamp || Date.now(),
});
}
// Notification was clicked, i.e. "Open" or "Dismiss" clicked
self.addEventListener('notificationclick', (event) => {
console.log('SW', 'notificationclick', event.action);
// Android doesn't close the notification when you click on it
// See: http://crbug.com/463146
event.notification.close();
let data = getNotificationMessage(event.notification);;
let windowMessage = {
action: 'serviceworker-notification',
data: data,
};
// KaiOS 2.5
if (clients && 'openApp' in clients) {
event.waitUntil(
Promise.all([
sendWindowMessage(windowMessage), // Focus existing window
clients.openApp({ msg: data }), // Open app
])
);
}
});