This repository has been archived by the owner on Oct 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathpush-sw.js
91 lines (85 loc) · 2.91 KB
/
push-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
86
87
88
89
90
91
/*
* Push notificiations ServiceWorker
*
* NOTE(@mxstbr): This only gets updated if you change the filename, not if you
* update the contents. Make sure to change the version number in the filename
* after updating the code!
*/
// A new notification is coming in, yay!
// eslint-disable-next-line
self.addEventListener('push', function(event) {
var notificationData = {};
try {
notificationData = event.data.json();
} catch (e) {
console.log('event.data.json() failed', e);
// 🚨 We either got no data or it's malformatted, ABORT ABORT ABORT
return;
}
// Check if the user is looking at Spectrum right now and don't show a notification
event.waitUntil(
clients
.matchAll({
type: 'window',
includeUncontrolled: true,
})
.then(windowClients => {
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
// The user is looking at Spectrum right now abort showing the notification!
// (except for if we're on localhost, i.e. in development)
if (
windowClient.focused &&
// eslint-disable-next-line
!(self.registration.scope.indexOf('http://localhost:3000') === 0)
) {
return;
}
}
// eslint-disable-next-line
return self.registration.showNotification(notificationData.title, {
vibrate: [200],
icon: '/img/apple-icon-144x144-precomposed.png',
badge: '/img/badge.png',
body: notificationData.body,
title: notificationData.title,
timestamp: notificationData.timestamp,
image: notificationData.image,
tag: notificationData.tag,
data: notificationData.data,
// If we don't set a tag and set renotify to true this'll throw an error
// renotify: notificationData.renotify || !!notificationData.tag,
});
})
);
});
// On notification click
// eslint-disable-next-line
self.addEventListener('notificationclick', function(event) {
event.notification.close();
const urlToOpen =
event.notification.data && event.notification.data.href
? // eslint-disable-next-line
new URL(event.notification.data.href, self.location.origin).href
: '/';
// see if the current is open and if it is focus it
event.waitUntil(
// eslint-disable-next-line
self.clients
.matchAll({
type: 'window',
includeUncontrolled: true,
})
.then(function(clientList) {
// If there is an open Spectrum.chat window navigate to the notification href
if (clientList.length > 0) {
return clientList[0]
.focus()
.then(client => client.navigate(urlToOpen));
}
// If there's no open Spectrum.chat window open a new one
// eslint-disable-next-line
return self.clients.openWindow(urlToOpen);
})
);
});