-
-
Notifications
You must be signed in to change notification settings - Fork 263
/
serviceWorker.js
224 lines (196 loc) · 6.32 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
//Cache polyfil to support cacheAPI in all browsers
importScripts('./cache-polyfill.js');
var cacheName = 'cache-v4';
//Files to save in cache
var files = [
'./',
'./index.html?utm=homescreen', //SW treats query string as new request
'https://fonts.googleapis.com/css?family=Roboto:200,300,400,500,700', //caching 3rd party content
'./css/styles.css',
'./images/icons/android-chrome-192x192.png',
'./images/push-on.png',
'./images/push-off.png',
'./images/icons/favicon-16x16.png',
'./images/icons/favicon-32x32.png',
'./js/main.js',
'./js/app.js',
'./js/offline.js',
'./js/push.js',
'./js/sync.js',
'./js/toast.js',
'./js/share.js',
'./js/menu.js',
'./manifest.json'
];
//Adding `install` event listener
self.addEventListener('install', (event) => {
console.info('Event: Install');
event.waitUntil(
caches.open(cacheName)
.then((cache) => {
//[] of files to cache & if any of the file not present `addAll` will fail
return cache.addAll(files)
.then(() => {
console.info('All files are cached');
return self.skipWaiting(); //To forces the waiting service worker to become the active service worker
})
.catch((error) => {
console.error('Failed to cache', error);
})
})
);
});
/*
FETCH EVENT: triggered for every request made by index page, after install.
*/
//Adding `fetch` event listener
self.addEventListener('fetch', (event) => {
console.info('Event: Fetch');
var request = event.request;
var url = new URL(request.url);
if (url.origin === location.origin) {
// Static files cache
event.respondWith(cacheFirst(request));
} else {
// Dynamic API cache
event.respondWith(networkFirst(request));
}
// // Checking for navigation preload response
// if (event.preloadResponse) {
// console.info('Using navigation preload');
// return response;
// }
});
async function cacheFirst(request) {
const cachedResponse = await caches.match(request);
return cachedResponse || fetch(request);
}
async function networkFirst(request) {
const dynamicCache = await caches.open(cacheName);
try {
const networkResponse = await fetch(request);
// Cache the dynamic API response
dynamicCache.put(request, networkResponse.clone()).catch((err) => {
console.warn(request.url + ': ' + err.message);
});
return networkResponse;
} catch (err) {
const cachedResponse = await dynamicCache.match(request);
return cachedResponse;
}
}
/*
ACTIVATE EVENT: triggered once after registering, also used to clean up caches.
*/
//Adding `activate` event listener
self.addEventListener('activate', (event) => {
console.info('Event: Activate');
//Navigation preload is help us make parallel request while service worker is booting up.
//Enable - chrome://flags/#enable-service-worker-navigation-preload
//Support - Chrome 57 beta (behing the flag)
//More info - https://developers.google.com/web/updates/2017/02/navigation-preload#the-problem
// Check if navigationPreload is supported or not
// if (self.registration.navigationPreload) {
// self.registration.navigationPreload.enable();
// }
// else if (!self.registration.navigationPreload) {
// console.info('Your browser does not support navigation preload.');
// }
//Remove old and unwanted caches
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cache) => {
if (cache !== cacheName) {
return caches.delete(cache); //Deleting the old cache (cache v1)
}
})
);
})
.then(function () {
console.info("Old caches are cleared!");
// To tell the service worker to activate current one
// instead of waiting for the old one to finish.
return self.clients.claim();
})
);
});
/*
PUSH EVENT: triggered everytime, when a push notification is received.
*/
//Adding `push` event listener
self.addEventListener('push', (event) => {
console.info('Event: Push');
var title = 'Push notification demo';
var body = {
'body': 'click to return to application',
'tag': 'demo',
'icon': './images/icons/apple-touch-icon.png',
'badge': './images/icons/apple-touch-icon.png',
//Custom actions buttons
'actions': [
{ 'action': 'yes', 'title': 'I ♥ this app!'},
{ 'action': 'no', 'title': 'I don\'t like this app'}
]
};
event.waitUntil(self.registration.showNotification(title, body));
});
/*
BACKGROUND SYNC EVENT: triggers after `bg sync` registration and page has network connection.
It will try and fetch github username, if its fulfills then sync is complete. If it fails,
another sync is scheduled to retry (will will also waits for network connection)
*/
self.addEventListener('sync', (event) => {
console.info('Event: Sync');
//Check registered sync name or emulated sync from devTools
if (event.tag === 'github' || event.tag === 'test-tag-from-devtools') {
event.waitUntil(
//To check all opened tabs and send postMessage to those tabs
self.clients.matchAll().then((all) => {
return all.map((client) => {
return client.postMessage('online'); //To make fetch request, check app.js - line no: 122
})
})
.catch((error) => {
console.error(error);
})
);
}
});
/*
NOTIFICATION EVENT: triggered when user click the notification.
*/
//Adding `notification` click event listener
self.addEventListener('notificationclick', (event) => {
var url = 'https://demopwa.in/';
//Listen to custom action buttons in push notification
if (event.action === 'yes') {
console.log('I ♥ this app!');
}
else if (event.action === 'no') {
console.warn('I don\'t like this app');
}
event.notification.close(); //Close the notification
//To open the app after clicking notification
event.waitUntil(
clients.matchAll({
type: 'window'
})
.then((clients) => {
for (var i = 0; i < clients.length; i++) {
var client = clients[i];
//If site is opened, focus to the site
if (client.url === url && 'focus' in client) {
return client.focus();
}
}
//If site is cannot be opened, open in new window
if (clients.openWindow) {
return clients.openWindow('/');
}
})
.catch((error) => {
console.error(error);
})
);
});