forked from NishikantaRay/studytub-PWA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.js
51 lines (45 loc) · 1.89 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
// documented by Neeraj Gupta - https://neerajgupta.codes
self.addEventListener("install", (event) => {
console.log("Service worker install event!");
// event.waitUntil will wait until innermost event is resolved
// waitUntil will prevent the browser to terminate the service worker process before promise is resolved
// read about waitUntil here - https://developer.mozilla.org/en-US/docs/Web/API/ExtendableEvent/waitUntil
event.waitUntil(
// Open cache(cacheName) from CacheStorage and if opened add all resourcesToPrecache in CacheStorage
caches
.open(cacheName)
.then((cache) => cache.addAll(resourcesToPrecache))
.catch((err) => console.log("Faled to precache", err))
);
});
self.addEventListener("activate", (event) => console.log("Activate event"));
// fetching files from either cache or network
self.addEventListener("fetch", (event) => {
// respondWith will prevent browser to directly go and do fetch request instead provide user with power to do task manually depending on promise
// read about respondWith here - https://developer.mozilla.org/en-US/docs/Web/API/FetchEvent/respondWith
event.respondWith(
caches
.match(event.request)
.then((cachedResponse) => cachedResponse || fetch(event.request)) //returning cache or if not available fetching from event
);
});
self.addEventListener("push", (event) => {
const title = "Yes, a message";
const body = "We have received a push message";
const tag = "simple-push-example-tag";
const options = {
body: body,
tag: tag,
};
event.waitUntil(self.registration.showNotification(title, options));
});
// Pre Caching resources
const cacheName = "cache-v1";
const resourcesToPrecache = [
"/",
"index.html",
"style.css",
"index.js",
"img/core-img/nanda.webp",
"manifest.json",
];