-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.js
160 lines (146 loc) · 4.22 KB
/
service-worker.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
// #3: Sync
importScripts('idb-keyval-min.js');
// Version 1.0
// #1: Cache files for offline support
const dataCacheName = 'cat-chat-v1';
const firebaseUrl = 'https://cat-chat-827fd.firebaseio.com';
const firebaseMessageUrl = `${firebaseUrl}/messages.json`;
const filesToCache = [
'/',
'/index.html',
'/styles.css',
'/subscribe.js',
'/chat.js',
'/idb-keyval-min.js',
'/images/unsplash.jpeg'
];
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(dataCacheName).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');
if (key !== dataCacheName) {
return caches.delete(key);
}
}));
})
);
});
//
self.addEventListener('fetch', function(event) {
console.log('[ServiceWorker] Fetch', event.request.url);
// If request includes firebase url and not cached, put in cache and return response
// Not recommended for frequently updated data, use sw-toolbox for more control
if (event.request.url.indexOf(firebaseUrl) === 0) {
event.respondWith(
caches.open(dataCacheName).then(function(cache) {
return cache.match(event.request).then(function (response) {
return response || fetch(event.request).then(function(response) {
cache.put(event.request, response.clone());
console.log('[ServiceWorker] Fetched&Cached Data');
return response;
});
});
})
);
} else {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
}
});
// #2: Add push support
self.addEventListener('push', function(event) {
console.log('Push message', event);
var title = 'MAIL';
// You can't send any data with a push message
event.waitUntil(
fetch(firebaseMessageUrl)
.then((response) => response.json())
.then((json) => {
// Get the last (newest) message
const sortedMessages = Object.keys(json)
.map((x) => json[x])
.sort((x, y) => x.timestamp < y.timestamp);
return self.registration.showNotification(title, {
'body': sortedMessages[0].value,
'icon': 'images/catwrap.jpg'
});
})
);
});
self.addEventListener('notificationclick', function(event) {
console.log('Notification click: tag', event.notification.tag);
// Android doesn't close the notification when you click it
// See http://crbug.com/463146
event.notification.close();
var url = 'http://localhost:8080/';
// 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);
}
})
);
});
// #3: Background sync
function broadcast(message) {
return clients.matchAll().then(function(clients) {
for (var client of clients) {
client.postMessage(message);
}
});
}
function sendMessage() {
return idbKeyval.get('message')
.then((message) => {
if(message){
return fetch(firebaseMessageUrl, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(message)
})
.then((res) => res.json())
.then((json) => {
broadcast({ name: json.name, message });
});
} else {
return Promise.resolve();
}
});
}
self.addEventListener('sync', function (event) {
console.log('[ServiceWorker] Sync', event);
if (event.tag === 'postMessage') {
event.waitUntil(sendMessage());
}
});