forked from matiboy/angular-browser-push-notifications
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathservice-worker-with-fetch.js
63 lines (55 loc) · 1.86 KB
/
service-worker-with-fetch.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
'use strict';
self.addEventListener('push', function(event) {
console.log('Received a push message', event);
var title = 'Anacondapp';
var icon = '/images/icon-192x192.png';
var tag = 'anacondapp'+Date.now();
var notificationPromise = event.currentTarget.registration.pushManager.getSubscription().then(function(sub) {
var id = sub.endpoint.split('/').pop();
return fetch('/communications/details?token='+id);
}).then(function(response){
return response.text();
}).then(function(body) {
return self.registration.showNotification(title, {
body: body,
icon: icon,
tag: tag
});
});
event.waitUntil(notificationPromise);
// Close after 5 seconds if still there - more browser like than mobile phone
notificationPromise.then(function() {
return new Promise(function(resolve){
setTimeout(resolve, 5000)
});
}).then(function() {
return event.currentTarget.registration.getNotifications();
}).then(function(notifications) {
for(var i=0;i<notifications.length;i++){
var notification = notifications[i];
if(notification.tag === tag){
notification.close();
break;
}
}
});
});
self.addEventListener('notificationclick', function(event) {
console.log('On notification click: ', event);
// Android doesn’t close the notification when you click on it
// See: http://crbug.com/463146
event.notification.close();
// 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];
if (client.url == '/' && 'focus' in client)
return client.focus();
}
if (clients.openWindow)
return clients.openWindow('/');
}));
});