-
Notifications
You must be signed in to change notification settings - Fork 48
/
WebPushManager.js
45 lines (38 loc) · 1.27 KB
/
WebPushManager.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
var WebPushManager = function(){
}
WebPushManager.prototype.start = function(callback) {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./service-worker.js')
.then(this.getRegistrationId(callback));
} else {
callback('Service workers aren\'t supported in this browser.', null);
}
}
WebPushManager.prototype.getRegistrationId = function (callback) {
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
var fb_messaging = firebase.messaging();
fb_messaging.useServiceWorker(serviceWorkerRegistration);
fb_messaging.requestPermission()
.then(function() {
console.log('Notification permission granted.');
fb_messaging.getToken()
.then(function(currentToken) {
if (currentToken) {
callback(null, currentToken);
}
})
.catch(function(err) {
callback(err)
});
})
.catch(function(err) {
console.log('Unable to get permission to notify. ', err);
callback(err);
});
});
}
WebPushManager.prototype.forceNotification = function(message) {
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
serviceWorkerRegistration.active.postMessage(message);
});
}