-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsw.js
More file actions
77 lines (72 loc) · 1.98 KB
/
sw.js
File metadata and controls
77 lines (72 loc) · 1.98 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// When the application is installed, pre-load items.
self.addEventListener('install', function(event) {
event.waitUntil(preLoad());
});
var preLoad = function(){
return caches.open('pwa-offline')
.then(function(cache) {
console.log('Caching offline page.');
return cache.addAll(['/offline/index.html']);
})
.catch(function(error)
{
console.log("Exception adding default cached files: " + error)
return Promise.reject("Could not cache offline page.");
});
}
self.addEventListener('fetch', function(event) {
if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') {
return;
}
if(("" + event.request.url).length == 0)
{
return;
}
// Skip data from other domains
if(!event.request.url.startsWith("https://developer.m-files.com"))
{
return;
}
event.respondWith(checkResponse(event.request).catch(function() {
console.log('Returning cached asset for ' + event.request.url);
return returnFromCache(event.request)}
));
event.waitUntil(addToCache(event.request));
});
var checkResponse = function(request){
return new Promise(function(fulfill, reject) {
fetch(request).then(function(response){
if(response.status !== 404) {
fulfill(response)
} else {
reject()
}
}, reject)
});
};
var addToCache = function(request){
if(request.bodyUsed || !request.url.startsWith("https://developer.m-files.com"))
return Promise.resolve();
return fetch(request.clone())
.then(function (response) {
return caches.open('pwa-offline').then(function (cache) {
return cache.put(request, response);
});
})
.catch(function(error)
{
console.log("Exception requesting file: " + error)
return Promise.reject("no match");
});
};
var returnFromCache = function(request){
return caches.open('pwa-offline').then(function (cache) {
return cache.match(request).then(function (matching) {
if(!matching || matching.status == 404) {
return cache.match('/offline/index.html')
} else {
return matching
}
});
});
};