This repository has been archived by the owner on Apr 17, 2020. It is now read-only.
forked from blockscoped/hn-riot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
70 lines (64 loc) · 2.09 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
const CACHE_NAME = 'riot-hackernews';
const expectedCaches = [CACHE_NAME];
self.addEventListener('install', (event) => {
self.skipWaiting();
});
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
event.respondWith(
caches.match(event.request).then(resp => resp || fetch(event.request).then(response =>
caches.open(CACHE_NAME).then((cache) => {
if (event.request.url.match(/(locations|subscriptions|notifications)/) === null) {
cache.put(event.request, response.clone());
}
return response;
})
))
);
});
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then(keys => Promise.all(
keys.map(key => {
if (!expectedCaches.includes(key)) {
return caches.delete(key);
}
})
)).then(() => {
console.log(`${CACHE_NAME} now ready to handle fetches!`);
return clients.claim();
})
);
});
self.addEventListener('push', (event) => {
event.waitUntil(
self.registration.pushManager.getSubscription().then((subscription) => {
const subscriptionId = subscription.endpoint.replace('https://android.googleapis.com/gcm/send/', '', subscription);
return fetch('./notifications', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
subscriptionId,
}),
})
.then(response => response.json())
.then((data) => {
if (data.value === null) return false;
const title = data.value.title;
const body = `${(data.value.body).substring(0, 32)}...`;
const icon = `./app/assets/icon/${data.value.icon}.jpg`;
const badge = `./app/assets/badge/${data.value.icon}.png`;
const tag = data.value.tag;
return self.registration.showNotification(title, { body, icon, badge, tag });
});
})
);
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
event.waitUntil(
clients.openWindow('https://saurshaz.github.io/riot-hn/')
);
});