-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserviceworker.js
83 lines (76 loc) · 2.13 KB
/
serviceworker.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
//serviceworker
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("push", function (event) {
if (event && event.data) {
try {
var data = event.data.json();
console.log(data.method);
if (data && data.method === "pushMessage") {
console.log("Push notification sent");
self.registration.showNotification("ShoppingMart", {
body: data.message,
});
}
} catch (error) {
console.error("Error parsing push data:", error);
}
}
});
self.addEventListener("sync", (event) => {
if (event.tag === "syncMessage") {
console.log("Sync successful!");
}
});
var preLoad = function () {
return caches.open("offline").then(function (cache) {
// caching index and important routes
return cache.addAll(["/index.html", "/images/10.jpg", "/css/style.css"]);
});
};
var checkResponse = function (request) {
return new Promise(function (fulfill, reject) {
fetch(request)
.then(function (response) {
if (response.status !== 404) {
fulfill(response);
} else {
reject(new Error("Response not found"));
}
})
.catch(function (error) {
reject(error);
});
});
};
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("offline.html");
} else {
return matching;
}
});
});
};
var addToCache = function (request) {
return caches.open("offline").then(function (cache) {
return fetch(request).then(function (response) {
return cache.put(request, response.clone()).then(function () {
return response;
});
});
});
};