-
Notifications
You must be signed in to change notification settings - Fork 1
/
sw.js
70 lines (64 loc) · 1.79 KB
/
sw.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
/* global self, clients */
var TITLE = 'Message from electric_g';
var BODY = 'Default push message';
var ICON = 'icon.png';
var OPEN_URL = location.href.replace('sw.js', '');
self.addEventListener('install', function(event) {
self.skipWaiting();
console.log('Installed', event);
});
self.addEventListener('activate', function(event) {
console.log('Activated', event);
});
self.addEventListener('push', function(event) {
console.log('Received push');
var notificationTitle = TITLE;
var notificationOptions = {
body: BODY,
icon: ICON
};
if (event.data) {
var msg = {
t: TITLE,
b: BODY
};
try {
var tmp = JSON.parse(event.data.text());
msg.t = tmp.t || msg.t;
msg.b = tmp.b || msg.b;
} catch(e) {}
notificationTitle = msg.t;
notificationOptions.body = msg.b;
}
event.waitUntil(
self.registration.showNotification(notificationTitle, notificationOptions)
);
});
self.addEventListener('notificationclick', function(event) {
console.log('Notification click', event.notification);
// Android doesn't close the notification when you click it
// See http://crbug.com/463146
event.notification.close();
var url = OPEN_URL;
// Check if there's already a tab open with this URL.
// If yes: focus on the tab.
// If no: open a tab with the URL.
event.waitUntil(
clients.matchAll({
type: 'window'
})
.then(function(windowClients) {
console.log('WindowClients', windowClients);
for (var i = 0; i < windowClients.length; i++) {
var client = windowClients[i];
console.log('WindowClient', client);
if (client.url === url && 'focus' in client) {
return client.focus();
}
}
if (clients.openWindow) {
return clients.openWindow(url);
}
})
);
});