-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathserviceWorker.js
99 lines (88 loc) · 2.64 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var cacheName = 'cache-v3';
/*
* Files to be served from cache
*/
var files = [
'./',
'./index.html',
'./css/styles.css',
'/js/notify.js',
'/js/app.js',
'/js/sync.js',
'/js/push.js',
'/js/networkChange.js',
'./manifest.json',
'./images/icon_16.png',
'./images/icon_32.png',
'./images/icon_192.png',
'./images/icon_256.png',
'./images/icon_512.png',
"https://use.fontawesome.com/releases/v5.2.0/css/all.css"
];
self.addEventListener('install', (event) => {
console.info('Installing Service Worker');
event.waitUntil(
caches.open(cacheName)
.then((cache) => {
return cache.addAll(files)
.then(() => {
console.info('Sucessfully Cached');
return self.skipWaiting();
})
.catch((error) => {
console.error('Failed to cache', error);
})
})
);
});
self.addEventListener('activate', (event) => {
console.info('Activating service worker');
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cache) => {
if (cache !== cacheName) {
return caches.delete(cache);
}
})
);
}).then(function () {
return self.clients.claim();
})
);
});
self.addEventListener('fetch', (event) => {
console.info('Event: Fetch');
var request = event.request;
event.respondWith(
/**
* Add caching strategy here
* e.g. Cache first
*/
caches.match(request).then((response) => {
if (response) {
return response;
}
return fetch(request).then((response) => {
var responseToCache = response.clone();
caches.open(cacheName).then((cache) => {
cache.put(request, responseToCache).catch((err) => {
console.warn(request.url + ': ' + err.message);
});
});
return response;
});
})
);
});
self.addEventListener('push', (event) => {
console.info('Event: Push', event);
event.waitUntil(self.registration.showNotification("test notification", {body: event.body}));
});
self.addEventListener('sync', function(event) {
console.info('Event: Sync', event);
/**
* Add logic to send requests to backend when sync happens
*/
self.registration.showNotification("Syncing Now");
});