-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsw-template.js
104 lines (87 loc) · 2.97 KB
/
sw-template.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
var cacheName = '{{cacheName}}';
var filesToCache = [ {{#each filesToCache}}
'{{.}}'{{#unless @last}},{{/unless}}
{{/each}}
];
self.addEventListener('install', function (e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(cacheName).then(function (cache) {
console.log('[ServiceWorker] Caching app shell');
return cache.addAll(filesToCache);
})
);
});
self.addEventListener('activate', function (e) {
console.log('[ServiceWorker] Activate');
e.waitUntil(
caches.keys().then(function (keyList) {
return Promise.all(keyList.map(function (key) {
console.log('[ServiceWorker] Removing old cache', key);
if (key !== cacheName) {
return caches.delete(key);
}
}));
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(
// Try the cache
caches.match(event.request).then(function(response) {
// Fall back to network
return response || fetch(event.request);
}).catch(function() {
// If both fail, show a generic fallback:
// return caches.match('/offline.html');
// However, in reality you'd have many different
// fallbacks, depending on URL & headers.
// Eg, a fallback silhouette image for avatars.
sendMessageToAllClients("failingServer");
return new Response("Can't Connect to server");
})
);
});
self.addEventListener('message', function (e) {
if (e.data == 'skipWaiting') {
self.skipWaiting();
}
});
self.addEventListener('push', function(event) {
console.log('[Service Worker] Push Received.');
console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
var jsonObject = JSON.parse(event.data.text());
const title = jsonObject.title;
const options = {
body: jsonObject.description,
icon: jsonObject.image
};
event.waitUntil(self.registration.showNotification(title, options));
});
self.addEventListener('notificationclick', function(event) {
console.log('[Service Worker] Notification click Received.');
event.notification.close();
event.waitUntil(
clients.openWindow('https://www.google.com.ph')
);
});
function sendMessageToClient(client, message){
return new Promise(function(resolve, reject){
var messageChannel = new MessageChannel();
messageChannel.port1.onmessage = function(e){
if(e.data.error){
reject(e.data.error);
}else{
resolve(e.data);
}
};
client.postMessage(message, [messageChannel.port2]);
});
}
function sendMessageToAllClients(msg){
clients.matchAll().then(clients => {
clients.forEach(client => {
sendMessageToClient(client, msg).then(m => console.log("SW Received Message: "+m));
})
})
}