-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathservice-worker.js
82 lines (73 loc) · 2.28 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
self.addEventListener("install", function (event) {
event.waitUntil(preLoad());
});
self.addEventListener("fetch", function (event) {
event.respondWith(checkResponse(event.request).catch(function () {
console.log("Fetch from cache successful!")
return returnFromCache(event.request);
}));
console.log("Fetch successful!")
event.waitUntil(addToCache(event.request));
});
self.addEventListener('sync', event => {
if (event.tag === 'Sync from cache') {
console.log("Sync successful!")
}
});
self.addEventListener('push', function (event) {
if (event && event.data) {
var data = event.data.json();
if (data.method == "PushMessageData") {
console.log("Push notification sent");
event.waitUntil(self.registration.showNotification("RED STORE", {body: data.message}))
}
}
})
var filesToCache = [
'/index.html',
'/checkout.html',
'/contact.html',
'/cart.html',
'/detail.html',
'/shop.html'
];
var preLoad = function () {
return caches.open("offline").then(function (cache) { // caching index and important routes
return cache.addAll(filesToCache);
});
};
self.addEventListener("fetch", function (event) {
event.respondWith(checkResponse(event.request).catch(function () {
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) {
return caches.open("offline").then(function (cache) {
return fetch(request).then(function (response) {
return cache.put(request, response);
});
});
};
var returnFromCache = function (request) {
return caches.open("offline").then(function (cache) {
return cache.match(request).then(function (matching) {
if (! matching || matching.status == 404) {
return cache.match("index.html");
} else {
return matching;
}
});
});
};