-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
94 lines (72 loc) · 2.59 KB
/
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
92
93
94
const eventsGate = 'https://e.rtblab.online' // #Change to your eventsapp url
self.addEventListener('push', function(event) {
let notificationData = {};
try {
notificationData = event.data.json();
} catch (e) {
notificationData = {
title: 'Default title',
options: {
body: 'Default message',
icon: 'default-icon.png'
}
};
}
if (notificationData.options.data.campaign_id) {
fetch(eventsGate + '/events/impression/' + notificationData.options.data.campaign_id, {mode: 'no-cors'})
.then(r => {
console.log('[sw] success fetch impcb')
})
.catch(err => {
console.warn('[sw] error fetch impcb', err)
})
}
event.waitUntil(
self.registration.showNotification(notificationData.title, notificationData.options)
);
});
self.addEventListener('notificationclick', function(event) {
event.notification.close()
let originalUrl = '/', id = ''
if (!event.notification.data) {
console.log('[sw] notificationclick: missed event.notification.data')
return
}
if (event.notification.data.url) {
let navigationUrl = event.notification.data.url
event.waitUntil(
clients.matchAll({ type: 'window' })
.then(clients => clients.filter(client => client.url === originalUrl))
.then(matchingClients => {
if (matchingClients[0]) {
return matchingClients[0].navigate(navigationUrl).then(client => client.focus())
}
return clients.openWindow(navigationUrl)
})
)
}
if (event.notification.data.campaign_id) {
fetch(eventsGate + '/events/click/' + event.notification.data.campaign_id, {mode: 'no-cors'})
.then(r => {
console.log('[sw] success fetch clickcb')
})
.catch(err => {
console.warn('[sw] error fetch clickcb', err)
})
}
});
self.addEventListener('notificationclose', function (event) {
if (!event.notification.data) {
console.log('[sw] notificationclose: missed event.notification.data')
return
}
if (event.notification.data.campaign_id) {
fetch( eventsGate + '/events/close/' + event.notification.data.campaign_id, {mode: 'no-cors'})
.then(r => {
console.log('[sw] success fetch closecb')
})
.catch(err => {
console.warn('[sw] error fetch closecb', err)
})
}
})