-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice-worker.js
94 lines (85 loc) · 2.92 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
94
addEventListener('backgroundfetchsuccess', event => {
console.log('[Service Worker]: Background Fetch Success', event.registration);
event.waitUntil(
(async function() {
try {
// Iterating the records to populate the cache
const cache = await caches.open(event.registration.id);
const records = await event.registration.matchAll();
const promises = records.map(async record => {
const response = await record.responseReady;
await cache.put(record.request, response);
});
await Promise.all(promises);
// [Optional] This could be an API call to our backend
let assetsDataResponse = await fetch(
`/assets/${event.registration.id}-data.json`
);
let assetsData = await assetsDataResponse.json();
// Updating UI
await event.updateUI({
title: `${assetsData.title} is ready`,
icons: assetsData.icons
});
} catch (err) {
await event.updateUI({
title: `${assetsData.title} failed: ${
event.registration.failureReason
}`
});
}
})()
);
});
addEventListener('backgroundfetchfail', event => {
console.log('[Service Worker]: Background Fetch Fail', event.registration);
event.waitUntil(
(async function() {
try {
const cache = await caches.open(event.registration.id);
const records = await event.registration.matchAll();
const promises = records.map(async record => {
const response = await record.responseReady;
if (response && response.ok) {
await cache.put(record.request, response);
}
});
await Promise.all(promises);
} finally {
// [Optional] This could be an API call to our backend
let assetsDataResponse = await fetch(
`/assets/${event.registration.id}-data.json`
);
let assetsData = await assetsDataResponse.json();
// Updating UI
await event.updateUI({
title: `${assetsData.title} failed: ${
event.registration.failureReason
}`
});
}
})()
);
});
addEventListener('backgroundfetchabort', event => {
console.log('[Service Worker]: Background Fetch Abort', event.registration);
console.error('Aborted by the user. No data was saved.');
});
addEventListener('backgroundfetchclick', event => {
console.log('[Service Worker]: Background Fetch Click', event.registration);
event.waitUntil(
(async function() {
let assetsDataResponse = await fetch(
`/assets/${event.registration.id}-data.json`
);
let assetsData = await assetsDataResponse.json();
clients.openWindow(assetsData.descriptionUrl);
})()
);
});
self.addEventListener('install', event => {
console.log('[Service Worker]: Installed');
});
self.addEventListener('activate', event => {
console.log('[Service Worker]: Active');
});