-
Notifications
You must be signed in to change notification settings - Fork 1
/
pushbots-chrome.js
executable file
·142 lines (117 loc) · 4.68 KB
/
pushbots-chrome.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
//Service worker file name
var serviceWorkerFile = './service-worker.js',
logging = true,
application_id = "PUSHBOTS_APP_ID",
pushbots_url = "https://api.pushbots.com/";
// Once the service worker is registered set the initial state
function initialise() {
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
var push_supported = (!!('PushManager' in window) || !!navigator.push)
&& !!window.Notification
&& !!navigator.serviceWorker
&& !!('showNotification' in ServiceWorkerRegistration.prototype);
//Check if Push messaging && serviceWorker && Notifications are supported in the browser
if(push_supported && isChrome){
var notificationStatusSetBefore = Notification.permission != "default";
if(logging) console.log("Notification permission status:", Notification.permission);
Notification.requestPermission(function(result) {
if (result === 'denied') {
if(logging) console.log('Permission was denied.');
return;
}else if( result === 'granted'){
//Register Notifications serviceWorker
navigator.serviceWorker.register(serviceWorkerFile).then(function(serviceWorkerRegistration) {
if(logging) console.log('Yey!', serviceWorkerRegistration);
if (notificationStatusSetBefore) {
serviceWorkerRegistration.pushManager.subscribe({userVisibleOnly: true}).then(function(subscription) {
// The subscription was successful
if(logging) console.log(subscription);
var token = endpointWorkaround(subscription);
//Register the token on Pushbots
try {
var xmlhttp = new XMLHttpRequest();
var jsonBody = JSON.stringify({
"token":token,
"platform":2,
"tz": Intl.DateTimeFormat().resolved.timeZone,
"locale" : window.navigator.language || 'en'
});
xmlhttp.open('PUT', pushbots_url + 'deviceToken');
xmlhttp.setRequestHeader('X-pushbots-appid', application_id);
xmlhttp.setRequestHeader('content-type', 'application/json; charset=UTF-8');
xmlhttp.onload = function(){
if(this.status === 200){
console.log("Updated info on Pushbots successfully.");
}else if(this.status === 201){
console.log("Registered on Pushbots successfully.");
}else{
console.warn("Status code" + this.status + ": error.")
}
};
xmlhttp.onerror = function(e){
console.log("Error occured: ", e);
};
xmlhttp.send(jsonBody);
} catch(e) {
console.log('Cannot register on Pushbots: ' + e);
}
}).catch(function(e) {
if (Notification.permission === 'denied') {
// The user denied the notification permission which
// means we failed to subscribe and the user will need
// to manually change the notification permission to
// subscribe to push messages
if(logging) console.warn('Permission for Notifications was denied');
} else {
// A problem occurred with the subscription; common reasons
// include network errors, and lacking gcm_sender_id and/or
// gcm_user_visible_only in the manifest.
if(logging) console.error('Unable to subscribe to push.', e);
}
});
}else{
//Refresh the page to enable serviceWorker for the first time
setTimeout(function() {
window.location.href = window.location.href;
}, 200);
}
}).catch(function(err) {
if(logging) console.log('Boo!', err);
});
}
});
}else{
console.warn("Push messaging is not supported in this browser.");
}
}
// This method handles the removal of subscriptionId
// in Chrome 44 by concatenating the subscription Id
// to the subscription endpoint
function endpointWorkaround(pushSubscription) {
// Chrome 42 + 43 will not have the subscriptionId attached
// to the endpoint.
if (pushSubscription.subscriptionId) {
// Handle version 42 where you have separate subId and Endpoint
return pushSubscription.subscriptionId;
}else{
return pushSubscription.endpoint.split('/').pop();
}
}
//Initialize Notifications
if ( document.readyState === "complete" ) {
initialise();
}else{
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
window.addEventListener( "load", initialise, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
initialise();
}
});
}
}