-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathservice-worker.js
93 lines (86 loc) · 2.45 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// true in production
var doCache = true;
// name cash
var CACHE_NAME = 'my-pwa-cache-v2';
// delete cash
self.addEventListener('activate', event => {
const cacheWhitelist = [CACHE_NAME];
event.waitUntil(
caches.keys()
.then(keyList =>
Promise.all(keyList.map(key => {
if (!cacheWhitelist.includes(key)) {
console.log('Deleting cache: ' + key)
return caches.delete(key);
}
}))
)
);
});
self.addEventListener('install', function(event) {
if (doCache) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
fetch('/manifest.json')
.then(response => {
response.json()
})
.then(assets => {
const urlsToCache = [
'',
]
cache.addAll(urlsToCache)
console.log('cached');
})
})
);
}
});
self.addEventListener('fetch', function(event) {
if (doCache) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
}
});
self.addEventListener('push', function(event) {
var body;
if (event.data){
body = event.data.json();
}
if (!body) return;
var options = {
body: body.message,
icon: body.icon,
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
primaryKey: 1
},
};
if (body.link){
options.actions = [
{action: 'show', title: body.show.title, icon:body.show.icon},
{action: 'close', title: body.close.title, icon:body.close.icon},
];
options.data.link = body.link;
}
if (body.requireInteraction){
options.requireInteraction = true;
}
event.waitUntil(
self.registration.showNotification(body.title, options)
);
});
self.addEventListener('notificationclick', function(event) {
if (!event.action) return;
if (event.action == 'show'){
var client = clients.openWindow(event.notification.data.link);
event.waitUntil(client);
} else {
event.notification.close();
}
});