-
Notifications
You must be signed in to change notification settings - Fork 91
/
app.js
286 lines (247 loc) · 9.24 KB
/
app.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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
firebase.initializeApp({
messagingSenderId: '448358493027'
});
var bt_register = $('#register');
var bt_delete = $('#delete');
var token = $('#token');
var form = $('#notification');
var massage_id = $('#massage_id');
var massage_row = $('#massage_row');
var info = $('#info');
var info_message = $('#info-message');
var alert = $('#alert');
var alert_message = $('#alert-message');
var input_body = $('#body');
var timerId = setInterval(setNotificationDemoBody, 10000);
function setNotificationDemoBody() {
if (input_body.val().search(/^It's found today at \d\d:\d\d$/i) !== -1) {
var now = new Date();
input_body.val('It\'s found today at ' + now.getHours() + ':' + addZero(now.getMinutes()));
} else {
clearInterval(timerId);
}
}
function addZero(i) {
return i > 9 ? i : '0' + i;
}
setNotificationDemoBody();
resetUI();
if (
'Notification' in window &&
'serviceWorker' in navigator &&
'localStorage' in window &&
'fetch' in window &&
'postMessage' in window
) {
var messaging = firebase.messaging();
// already granted
if (Notification.permission === 'granted') {
getToken();
}
// get permission on subscribe only once
bt_register.on('click', function() {
getToken();
});
bt_delete.on('click', function() {
// Delete Instance ID token.
messaging.getToken()
.then(function(currentToken) {
messaging.deleteToken(currentToken)
.then(function() {
console.log('Token deleted');
setTokenSentToServer(false);
// Once token is deleted update UI.
resetUI();
})
.catch(function(error) {
showError('Unable to delete token', error);
});
})
.catch(function(error) {
showError('Error retrieving Instance ID token', error);
});
});
form.on('submit', function(event) {
event.preventDefault();
var notification = {};
form.find('input').each(function () {
var input = $(this);
notification[input.attr('name')] = input.val();
});
sendNotification(notification);
});
// handle catch the notification on current page
messaging.onMessage(function(payload) {
console.log('Message received', payload);
info.show();
info_message
.text('')
.append('<strong>'+payload.data.title+'</strong>')
.append('<em>'+payload.data.body+'</em>')
;
// register fake ServiceWorker for show notification on mobile devices
navigator.serviceWorker.register('/serviceworker/firebase-messaging-sw.js');
Notification.requestPermission(function(permission) {
if (permission === 'granted') {
navigator.serviceWorker.ready.then(function(registration) {
// Copy data object to get parameters in the click handler
payload.data.data = JSON.parse(JSON.stringify(payload.data));
registration.showNotification(payload.data.title, payload.data);
}).catch(function(error) {
// registration failed :(
showError('ServiceWorker registration failed', error);
});
}
});
});
// Callback fired if Instance ID token is updated.
messaging.onTokenRefresh(function() {
messaging.getToken()
.then(function(refreshedToken) {
console.log('Token refreshed');
// Send Instance ID token to app server.
sendTokenToServer(refreshedToken);
updateUIForPushEnabled(refreshedToken);
})
.catch(function(error) {
showError('Unable to retrieve refreshed token', error);
});
});
} else {
if (!('Notification' in window)) {
showError('Notification not supported');
} else if (!('serviceWorker' in navigator)) {
showError('ServiceWorker not supported');
} else if (!('localStorage' in window)) {
showError('LocalStorage not supported');
} else if (!('fetch' in window)) {
showError('fetch not supported');
} else if (!('postMessage' in window)) {
showError('postMessage not supported');
}
console.warn('This browser does not support desktop notification.');
console.log('Is HTTPS', window.location.protocol === 'https:');
console.log('Support Notification', 'Notification' in window);
console.log('Support ServiceWorker', 'serviceWorker' in navigator);
console.log('Support LocalStorage', 'localStorage' in window);
console.log('Support fetch', 'fetch' in window);
console.log('Support postMessage', 'postMessage' in window);
updateUIForPushPermissionRequired();
}
function getToken() {
messaging.requestPermission()
.then(function() {
// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
messaging.getToken()
.then(function(currentToken) {
if (currentToken) {
sendTokenToServer(currentToken);
updateUIForPushEnabled(currentToken);
} else {
showError('No Instance ID token available. Request permission to generate one');
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
}
})
.catch(function(error) {
showError('An error occurred while retrieving token', error);
updateUIForPushPermissionRequired();
setTokenSentToServer(false);
});
})
.catch(function(error) {
showError('Unable to get permission to notify', error);
});
}
function sendNotification(notification) {
var key = 'AAAAaGQ_q2M:APA91bGCEOduj8HM6gP24w2LEnesqM2zkL_qx2PJUSBjjeGSdJhCrDoJf_WbT7wpQZrynHlESAoZ1VHX9Nro6W_tqpJ3Aw-A292SVe_4Ho7tJQCQxSezDCoJsnqXjoaouMYIwr34vZTs';
console.log('Send notification', notification);
// hide last notification data
info.hide();
massage_row.hide();
messaging.getToken()
.then(function(currentToken) {
fetch('https://fcm.googleapis.com/fcm/send', {
method: 'POST',
headers: {
'Authorization': 'key=' + key,
'Content-Type': 'application/json'
},
body: JSON.stringify({
// Firebase loses 'image' from the notification.
// And you must see this: https://github.com/firebase/quickstart-js/issues/71
data: notification,
to: currentToken
})
}).then(function(response) {
return response.json();
}).then(function(json) {
console.log('Response', json);
if (json.success === 1) {
massage_row.show();
massage_id.text(json.results[0].message_id);
} else {
massage_row.hide();
massage_id.text(json.results[0].error);
}
}).catch(function(error) {
showError(error);
});
})
.catch(function(error) {
showError('Error retrieving Instance ID token', error);
});
}
// Send the Instance ID token your application server, so that it can:
// - send messages back to this app
// - subscribe/unsubscribe the token from topics
function sendTokenToServer(currentToken) {
if (!isTokenSentToServer(currentToken)) {
console.log('Sending token to server...');
// send current token to server
//$.post(url, {token: currentToken});
setTokenSentToServer(currentToken);
} else {
console.log('Token already sent to server so won\'t send it again unless it changes');
}
}
function isTokenSentToServer(currentToken) {
return window.localStorage.getItem('sentFirebaseMessagingToken') === currentToken;
}
function setTokenSentToServer(currentToken) {
if (currentToken) {
window.localStorage.setItem('sentFirebaseMessagingToken', currentToken);
} else {
window.localStorage.removeItem('sentFirebaseMessagingToken');
}
}
function updateUIForPushEnabled(currentToken) {
console.log(currentToken);
token.text(currentToken);
bt_register.hide();
bt_delete.show();
form.show();
}
function resetUI() {
token.text('');
bt_register.show();
bt_delete.hide();
form.hide();
massage_row.hide();
info.hide();
}
function updateUIForPushPermissionRequired() {
bt_register.attr('disabled', 'disabled');
resetUI();
}
function showError(error, error_data) {
alert.show();
if (typeof error_data !== "undefined") {
alert_message.html(error + '<br><pre>' + JSON.stringify(error_data) + '</pre>');
console.error(error, error_data);
} else {
alert_message.html(error);
console.error(error);
}
}