-
Notifications
You must be signed in to change notification settings - Fork 1
/
service-worker.js
79 lines (67 loc) · 2.12 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
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
The service worker responsible for the notifications.
Initialized in app.js, after the app renders.
**/
self.addEventListener('push', function(event) {
console.log('Received a push message', event, event.endpoint);
event.waitUntil(
self.registration.pushManager.getSubscription().then(
function(subscription){
return clients.matchAll({
type: "window"
}).then(function(clientList) {
if(clientList[0] && clientList[0].focused) return Promise.reject('focused');
return fetch('/api/getNotification', {
method: 'POST',
body: JSON.stringify(subscription),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(response){
return response.json();
})
.then(function(data){
var title = data.title;
var body = data.body;
var icon = data.icon;
var tag = data.tag;
var room = data.room;
return self.registration.showNotification(title, {
body: body,
icon: icon,
tag: tag,
data: {
room: room
}
})
})
.catch(function(err){
console.log('Service Worker error:' + err);
})
})
.catch(function(err){
console.log('window was focused!', err);
})
}
)
);
});
self.addEventListener('notificationclick', function(event) {
var room = event.notification.data.room;
console.log('room is', room);
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(clients.matchAll({
type: "window"
}).then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
console.log(client.url)
if (client.url.indexOf('/'+room) > -1 && 'focus' in client)
return client.focus();
}
if (clients.openWindow)
return clients.openWindow('/'+room);
}));
});