This repository has been archived by the owner on Jul 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
sw.js
84 lines (72 loc) · 2.17 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
const currentCacheName = 'plantbuddies-0.02';
//trick to use parcel-plugin-sw-cache without workbox
//TODO: Replace with other plugin or custom code
const cacheFunction = {
precacheAndRoute: function(arr){
return arr
}
}
const cacheFilesObj = cacheFunction.precacheAndRoute([])
const cacheFiles = cacheFilesObj.map(function(item) {
return item['url'];
});
self.addEventListener('install', event => {
event.waitUntil(
caches.open(currentCacheName).then(cache => {
return cache.addAll(cacheFiles);
}).then(() => self.skipWaiting())
);
});
function fetchFromCache (request) {
return caches.match(request).then(response => {
if (!response) {
throw Error(`${request.url} not found in cache`);
}
return response;
});
}
function isNavigateRequest (request) {
return (request.mode === 'navigate' ||
(request.method === 'GET' &&
request.headers.get('accept').includes('text/html')));
}
function offlineRedirect () {
return caches.open(currentCacheName).then(cache => {
return cache.match('index.html');
});
}
self.addEventListener('fetch', event => {
if (event.request.url.startsWith(self.location.origin) || event.request.url.startsWith('https://plantbud') ) {
// console.log(event.request)
// console.log(event.request.url)
// if (event.request.url.indexOf('/plant' !== -1)) {
// console.log("route")
// }
event.respondWith(
caches.match(event.request).then(cachedResponse => {
if (cachedResponse) {
return cachedResponse;
}
return fetch(event.request).then(response => {
return response;
}).catch(() => offlineRedirect()) //maybe catch only navigation events with that
})
);
}
});
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (cacheName !== currentCacheName) {
console.log('[ServiceWorker] Deleting old cache:', cacheName);
return caches.delete(cacheName);
}
})
);
}).then(function() {
return self.clients.claim();
})
);
});