Repository navigation
Expand file tree
/
Copy pathsw.js
More file actions
62 lines (56 loc) · 1.5 KB
/
Copy pathsw.js
File metadata and controls
62 lines (56 loc) · 1.5 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
const CACHE_NAME = 'password.click-v1.1';
const FETCH_TIMEOUT = 5000; // 5 seconds
function fetchWithTimeout(request) {
return Promise.race([
fetch(request),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Network timeout')), FETCH_TIMEOUT)
)
]);
}
self.addEventListener('install', (event) => {
self.skipWaiting();
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => cache.add('/'))
);
});
self.addEventListener('activate', (event) => {
self.clients.claim();
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(
keys.map((key) => {
if (key !== CACHE_NAME) {
return caches.delete(key);
}
})
)
)
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
fetchWithTimeout(event.request)
.then((networkResponse) => {
const cloned = networkResponse.clone();
if (
networkResponse &&
(networkResponse.type === 'basic' || networkResponse.type === 'cors') &&
networkResponse.status === 200
) {
caches.open(CACHE_NAME).then((cache) => {
cache.put(event.request, cloned);
});
}
return networkResponse;
})
.catch(() => {
return caches.match(event.request).then((cachedResponse) => {
if (!cachedResponse && event.request.mode === 'navigate') {
return caches.match('/');
}
return cachedResponse;
});
})
);
});