-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.js
69 lines (64 loc) · 2.46 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
// https://github.com/GoogleChrome/samples/tree/gh-pages/service-worker recipes
const CACHE_VERSION = 1;
const CURRENT_CACHE = ['MultiQ_template_<template_name>' + CACHE_VERSION];
const urlsToCache = [
'/',
'https://newsapi.org/v2/top-headlines?country=se&apiKey=a8e51aef0ff44f1091af38f3798b6159'
];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CURRENT_CACHE).then(function(cache) {
return cache.addAll(urlsToCache);
})
);
self.skipWaiting();
});
self.addEventListener('activate', function(event) {
// Delete all caches that aren't named in CURRENT_CACHES.
// While there is only one cache in this example, the same logic will handle the case where
// there are multiple versioned caches.
let expectedCacheNamesSet = new Set(Object.values(CURRENT_CACHE));
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (!expectedCacheNamesSet.has(cacheName)) {
// If this cache name isn't present in the set of "expected" cache names, then delete it.
console.log('Deleting out of date cache:', cacheName);
return caches.delete(cacheName);
}
})
);
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(caches.match(event.request) // respond from cache if request is cached
.then(function(response) {
return fetch(event.request, { // fetch from network
// mode: 'cors',
// credentials: 'same-origin',
// headers: {
// 'Access-Control-Allow-Origin': '*',
// 'Content-Type': 'application/json',
// 'Accept': 'application/json'
// }
}).then(function(response) {
if (response && response.status < 400 && !response.url.includes('chrome-extension')) {
// response may be used only once, we need to save clone to put one copy in cache
// and serve second one
const responseClone = response.clone();
caches.open(CURRENT_CACHE).then(function(cache) {
cache.put(event.request, responseClone).catch((error) => console.warn('Cache error:', error.message));
});
}
return response;
}).catch(function(error) {
console.log('Error in fetch handler:', error);
// caches.match() always resolves
// but in case of success response will have value
return response;
});
}
));
});