forked from realtime-framework/ChromePushNotifications
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChromePushManager.js
More file actions
executable file
·55 lines (47 loc) · 1.76 KB
/
ChromePushManager.js
File metadata and controls
executable file
·55 lines (47 loc) · 1.76 KB
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
var ChromePushManager = function(serviceWorkerPath, callback){
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register(serviceWorkerPath)
.then(ChromePushManager.initialiseState(callback));
} else {
callback('Service workers aren\'t supported in this browser.', null);
}
}
ChromePushManager.initialiseState = function (callback) {
// Are Notifications supported in the service worker?
if (!('showNotification' in ServiceWorkerRegistration.prototype)) {
callback('Notifications aren\'t supported.', null);
} else if (Notification.permission === 'denied') {
callback('The user has blocked notifications.', null);
} else if (!('PushManager' in window)) {
callback('Push messaging isn\'t supported.', null);
} else {
ChromePushManager.subscribeBrowserId(callback);
}
}
ChromePushManager.subscribeBrowserId = function(callback) {
navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager.subscribe({userVisibleOnly: true})
.then(function(subscription) {
var register = ChromePushManager.getRegistrationId(subscription);
callback(null, register);
})
.catch(function(e) {
if (Notification.permission === 'denied') {
callback('Permission for Notifications was denied', null);
} else {
callback('Unable to subscribe to push.', null);
}
});
});
}
ChromePushManager.getRegistrationId = function(pushSubscription) {
if (pushSubscription.subscriptionId) {
return pushSubscription.subscriptionId;
}
var endpoint = 'https://android.googleapis.com/gcm/send/';
parts = pushSubscription.endpoint.split(endpoint);
if(parts.length > 1)
{
return parts[1];
}
}