forked from gokulkrishh/demo-progressive-web-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serviceWorker.js
196 lines (169 loc) · 5.3 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
'use strict';
//Cache polyfil to support cacheAPI in all browsers
importScripts('./cache-polyfill.js');
var cacheName = 'cache-v1';
//Files to save in cache
var files = [
'./',
'./index.html',
'./index.html?utm=homescreen', //SW treats query string as new page
'./css/styles.css',
'https://fonts.googleapis.com/css?family=Roboto:200,300,400,500,700', //caching 3rd party content
'./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/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', function (event) {
console.info('Event: Install');
event.waitUntil(
caches.open(cacheName)
.then(function (cache) {
//[] of files to cache & if any of the file not present `addAll` will fail
return cache.addAll(files)
.then(function () {
console.info('All files are cached');
return self.skipWaiting(); //To forces the waiting service worker to become the active service worker
})
.catch(function (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', function (event) {
console.info('Event: Fetch');
var request = event.request;
//Tell the browser to wait for newtwork request and respond with below
event.respondWith(
//If request is already in cache, return it
caches.match(request).then(function(response) {
if (response) {
return response;
}
//if request is not cached, add it to cache
return fetch(request).then(function(response) {
var responseToCache = response.clone();
caches.open(cacheName).then(
function(cache) {
cache.put(request, responseToCache).catch(function(err) {
console.warn(request.url + ': ' + err.message);
});
});
return response;
});
})
);
});
/*
ACTIVATE EVENT: triggered once after registering, also used to clean up caches.
*/
//Adding `activate` event listener
self.addEventListener('activate', function (event) {
console.info('Event: Activate');
//Remove old and unwanted caches
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cache) {
if (cache !== cacheName) { //cacheName = 'cache-v1'
return caches.delete(cache); //Deleting the cache
}
})
);
})
);
});
/*
PUSH EVENT: triggered everytime, when a push notification is received.
*/
//Adding `push` event listener
self.addEventListener('push', function(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', function(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(function (all) {
return all.map(function (client) {
return client.postMessage('online'); //To make fetch request, check app.js - line no: 122
})
})
.catch(function (error) {
console.error(error);
})
);
}
});
/*
NOTIFICATION EVENT: triggered when user click the notification.
*/
//Adding `notification` click event listener
self.addEventListener('notificationclick', function(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(function(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(function (error) {
console.error(error);
})
);
});