-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice-worker.js
58 lines (52 loc) · 2.15 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
// References:
// https://github.com/a7ul/web-push-demo
// https://github.com/TomasDePomas/notifier/blob/master/pushNotification/register.js
self.addEventListener('push', function (event) {
const notification = event.data.json();
return self.clients.matchAll({type: 'window'})
.then(function (_clients) {
for (let client of _clients) {
if (client.focused)
return; // Trust on in-app notification
}
// see compatibility https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification#browser_compatibility
// IOS 16 support will come in 2023 https://www.apple.com/ios/ios-16-preview/features/
self.registration.showNotification(notification.title, notification.opts)
.then(console.log)
.catch(console.error);
});
});
self.addEventListener('notificationclick', function (event) {
event.notification.close();
const action = event.action || ('data' in event.notification && event.notification.data.defaultAction);
event.waitUntil(self.clients.matchAll({type: 'window'}).then(function (clients) {
let focusedWindow;
let openWindow;
let actionMatch;
let fallback;
for (let client of clients) {
if (client.focused)
focusedWindow = client;
if (client.visibilityState === 'visible')
openWindow = client;
if (action && client.url.endsWith(action)) {
actionMatch = client;
}
fallback = client;
}
if (actionMatch) {
return actionMatch.focus();
} else if (focusedWindow) {
return action && focusedWindow.navigate(action);
} else if (openWindow) {
openWindow.focus();
return action && openWindow.navigate(action);
} else if (fallback) {
fallback.focus();
return action && fallback.navigate(action);
} else {
return self.clients.openWindow(action || '/notifications')
.then(client => client.focus());
}
}));
});