-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice-worker.js.example
More file actions
executable file
·64 lines (58 loc) · 2.39 KB
/
service-worker.js.example
File metadata and controls
executable file
·64 lines (58 loc) · 2.39 KB
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
/**
* Created by TomasDePomas on 10-1-2016.
*
* Make sure this file is served at <site root>/service-worker.js
* by placing this file in the root of your <project root>/public/ folder.
*
*/
var apiURL = '';
self.addEventListener('activate', function(event) {
self.apiURL = self.registration.active.scriptURL.split('?apiPath=')[1];
});
self.addEventListener('push', function(event) {
event.waitUntil(
self.registration.pushManager.getSubscription()
.then(function(subscription) {
if(subscription) {
var bits = subscription.endpoint.split('/')
registrationId = bits[bits.length -1];
fetch(self.apiURL + '/' + registrationId)
.then(function (response) {
if (response.status !== 200) {
throw new Error('Invalid status code from API: ' +
response.status);
}
return response.json();
})
.then(function (data) {
var message = data.length ? data[0] : false;
if(message){
fetch(self.apiURL + '/received/' + message._id);
var title = message.title ? message.title : 'Notification';
return self.registration.showNotification(title,
message
);
}else{
console.error('Message is empty');
}
})
.catch(function (err) {
console.error('A problem occurred finding the message: ', err);
})
} else {
console.error('No subscription found');
}
})
);
});
self.addEventListener('notificationclick', function(event) {
console.log(event);
event.notification.close();
event.waitUntil(clients.matchAll({
type: 'window'
}).then(function() {
var url = event.notification.link || '/';
if (clients.openWindow)
return clients.openWindow(url);
}));
});