/
firebase-messaging-sw.js
95 lines (84 loc) · 2.42 KB
/
firebase-messaging-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
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
/* global firebase */
importScripts('https://www.gstatic.com/firebasejs/4.13.0/firebase-app.js');
importScripts(
'https://www.gstatic.com/firebasejs/4.13.0/firebase-messaging.js'
);
importScripts('/environments/environment.js');
firebase.initializeApp(environment.firebase);
var messaging = firebase.messaging();
// Messaging
console.log('firebase-messaging-sw.js initialized');
messaging.setBackgroundMessageHandler(function(payload) {
const { message: body } = payload.data;
console.log(
'[firebase-messaging-sw.js] Received background message ',
payload
);
// Customize notification here
var notificationTitle = 'Background Message Title';
var notificationOptions = {
body,
icon:
'https://cdn.glitch.com/ab6d28c0-aafb-4f4c-a385-096869db91d7%2Flogo-logomark.png?1521808882093',
};
return self.registration.showNotification(
notificationTitle,
notificationOptions
);
});
// Establish cache
const CACHE_NAME = 'firelist-react-v0.0.0';
const urlsToCache = [
'/',
'/index.html',
'/style.css',
'/environments/environment.js',
];
self.addEventListener('install', event => {
console.log('install event', event);
const promise = caches
.open(CACHE_NAME)
.then(cache => {
console.table(urlsToCache);
return cache.addAll(urlsToCache);
})
.then(() => {
console.log('urls cached');
})
.catch(error => console.log(error));
event.waitUntil(promise);
});
// Access cache
self.addEventListener('fetch', function(event) {
event.respondWith(
caches
.match(event.request)
.then(response => response || cacheRequest(event))
);
});
function cacheRequest(event) {
const request = event.request.clone();
return fetch(request).then(response => {
console.log('response', response);
if (response && response.status == 200 && response.type == 'basic') {
caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, response.clone());
});
}
return response;
});
}
// Manage caches
self.addEventListener('activate', function(event) {
console.log('firebase-messaging-sw.js activated');
const promise = caches
.keys()
.then(cacheNames =>
Promise.all(
cacheNames.map(
cacheName => cacheName != CACHE_NAME && caches.delete(cacheName)
)
)
);
event.waitUntil(promise);
});