-
Notifications
You must be signed in to change notification settings - Fork 26
/
web-notification.js
405 lines (367 loc) · 13.9 KB
/
web-notification.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/*global define: false */
/**
* 'showNotification' callback.
*
* @callback ShowNotificationCallback
* @param {error} [error] - The error object in case of any error
* @param {function} [hide] - The hide notification function
*/
/**
* 'requestPermission' callback.
*
* @callback PermissionsRequestCallback
* @param {Boolean} granted - True if permission is granted, else false
*/
/**
* A simplified web notification API.
*
* @name webNotification
* @namespace webNotification
* @author Sagie Gur-Ari
*/
/**
* Initializes the web notification API.
*
* @function
* @memberof! webNotification
* @alias webNotification.initWebNotification
* @private
* @param {Object} global - The root context (window/global/...)
* @param {function} factory - Returns a new instance of the API
* @returns {Object} New instance of the API
*/
(function initWebNotification(global, factory) {
'use strict';
/*istanbul ignore next*/
const NotificationAPI = global.Notification || window.Notification;
const webNotification = factory(NotificationAPI);
/**
* Initializes the web notification API (only used for testing).
*
* @function
* @memberof! webNotification
* @alias webNotification.initWebNotificationFromContext
* @private
* @param {Object} context - The root context (window/global/...)
* @returns {Object} New instance of the API
*/
webNotification.initWebNotificationFromContext = function (context) {
return initWebNotification(context, factory);
};
if ((typeof define === 'function') && define.amd) {
define(function defineLib() {
return webNotification;
});
} else if ((typeof module === 'object') && module.exports) {
module.exports = webNotification;
} else {
global.webNotification = webNotification;
}
return webNotification;
}(this, function initWebNotification(NotificationAPI) {
'use strict';
let tagCounter = 0;
const webNotification = {};
/**
* The internal Notification library used by this library.
*
* @memberof! webNotification
* @alias webNotification.lib
* @private
*/
webNotification.lib = NotificationAPI;
/**
* True to enable automatic requesting of permissions if needed.
*
* @member {Boolean}
* @memberof! webNotification
* @alias webNotification.allowRequest
* @public
*/
webNotification.allowRequest = true; //true to enable automatic requesting of permissions if needed
/*eslint-disable func-name-matching*/
Object.defineProperty(webNotification, 'permissionGranted', {
/**
* Returns the permission granted value.
*
* @function
* @memberof! webNotification
* @private
* @returns {Boolean} True if permission is granted, else false
*/
get: function getPermission() {
const permission = NotificationAPI.permission;
/**
* True if permission is granted, else false.
*
* @memberof! webNotification
* @alias webNotification.permissionGranted
* @public
*/
let permissionGranted = false;
if (permission === 'granted') {
permissionGranted = true;
}
return permissionGranted;
}
});
/*eslint-enable func-name-matching*/
/**
* Empty function.
*
* @function
* @memberof! webNotification
* @alias webNotification.noop
* @private
* @returns {undefined} Undefined
*/
const noop = function () {
return undefined;
};
/**
* Checks if web notifications are permitted.
*
* @function
* @memberof! webNotification
* @alias webNotification.isEnabled
* @private
* @returns {Boolean} True if allowed to show web notifications
*/
const isEnabled = function () {
return webNotification.permissionGranted;
};
/**
* Displays the web notification and returning a 'hide' notification function.
*
* @function
* @memberof! webNotification
* @alias webNotification.createAndDisplayNotification
* @private
* @param {String} title - The notification title text (defaulted to empty string if null is provided)
* @param {Object} options - Holds the notification data (web notification API spec for more info)
* @param {String} [options.icon=/favicon.ico] - The notification icon (defaults to the website favicon.ico)
* @param {Number} [options.autoClose] - Auto closes the notification after the provided amount of millies (0 or undefined for no auto close)
* @param {function} [options.onClick] - An optional onclick event handler
* @param {Object} [options.serviceWorkerRegistration] - Optional service worker registeration used to show the notification
* @param {ShowNotificationCallback} callback - Invoked with either an error or the hide notification function
*/
const createAndDisplayNotification = function (title, options, callback) {
let autoClose = 0;
if (options.autoClose && (typeof options.autoClose === 'number')) {
autoClose = options.autoClose;
}
//defaults the notification icon to the website favicon.ico
if (!options.icon) {
options.icon = '/favicon.ico';
}
const onNotification = function (notification) {
//add onclick handler
if (options.onClick && notification) {
notification.onclick = options.onClick;
}
const hideNotification = function () {
notification.close();
};
if (autoClose) {
setTimeout(hideNotification, autoClose);
}
callback(null, hideNotification);
};
const serviceWorkerRegistration = options.serviceWorkerRegistration;
if (serviceWorkerRegistration) {
delete options.serviceWorkerRegistration;
if (!options.tag) {
tagCounter++;
options.tag = 'webnotification-' + Date.now() + '-' + tagCounter;
}
const tag = options.tag;
serviceWorkerRegistration.showNotification(title, options).then(function onCreate() {
serviceWorkerRegistration.getNotifications({
tag
}).then(function notificationsFetched(notifications) {
if (notifications && notifications.length) {
onNotification(notifications[0]);
} else {
callback(new Error('Unable to find notification.'));
}
}).catch(callback);
}).catch(callback);
} else {
let instance;
try {
instance = new NotificationAPI(title, options);
} catch (error) {
callback(error);
}
//in case of no errors
if (instance) {
onNotification(instance);
}
}
};
/**
* Returns an object with the show notification input.
*
* @function
* @memberof! webNotification
* @alias webNotification.parseInput
* @private
* @param {Array} argumentsArray - An array of all arguments provided to the show notification function
* @returns {Object} The parsed data
*/
const parseInput = function (argumentsArray) {
//callback is always the last argument
let callback = noop;
if (argumentsArray.length && (typeof argumentsArray[argumentsArray.length - 1] === 'function')) {
callback = argumentsArray.pop();
}
let title = null;
let options = null;
if (argumentsArray.length === 2) {
title = argumentsArray[0];
options = argumentsArray[1];
} else if (argumentsArray.length === 1) {
const value = argumentsArray.pop();
if (typeof value === 'string') {
title = value;
options = {};
} else {
title = '';
options = value;
}
}
//set defaults
title = title || '';
options = options || {};
return {
callback,
title,
options
};
};
/**
* Triggers the request permissions dialog in case permissions were not already granted.
*
* @function
* @memberof! webNotification
* @alias webNotification.requestPermission
* @public
* @param {PermissionsRequestCallback} callback - Called with the permissions result (true enabled, false disabled)
* @example
* ```js
* //manually ask for notification permissions (invoked automatically if needed and allowRequest=true)
* webNotification.requestPermission(function onRequest(granted) {
* if (granted) {
* console.log('Permission Granted.');
* } else {
* console.log('Permission Not Granted.');
* }
* });
* ```
*/
webNotification.requestPermission = function (callback) {
if (callback && typeof callback === 'function') {
if (isEnabled()) {
callback(true);
} else {
NotificationAPI.requestPermission(function onRequestDone() {
callback(isEnabled());
});
}
}
};
/**
* Shows the notification based on the provided input.<br>
* The callback invoked will get an error object (in case of an error, null in
* case of no errors) and a 'hide' function which can be used to hide the notification.
*
* @function
* @memberof! webNotification
* @alias webNotification.showNotification
* @public
* @param {String} [title] - The notification title text (defaulted to empty string if null is provided)
* @param {Object} [options] - Holds the notification data (web notification API spec for more info)
* @param {String} [options.icon=/favicon.ico] - The notification icon (defaults to the website favicon.ico)
* @param {Number} [options.autoClose] - Auto closes the notification after the provided amount of millies (0 or undefined for no auto close)
* @param {function} [options.onClick] - An optional onclick event handler
* @param {Object} [options.serviceWorkerRegistration] - Optional service worker registeration used to show the notification
* @param {ShowNotificationCallback} [callback] - Called after the show is handled.
* @example
* ```js
* //show web notification when button is clicked
* document.querySelector('.some-button').addEventListener('click', function onClick() {
* webNotification.showNotification('Example Notification', {
* body: 'Notification Text...',
* icon: 'my-icon.ico',
* onClick: function onNotificationClicked() {
* console.log('Notification clicked.');
* },
* autoClose: 4000 //auto close the notification after 4 seconds (you can manually close it via hide function)
* }, function onShow(error, hide) {
* if (error) {
* window.alert('Unable to show notification: ' + error.message);
* } else {
* console.log('Notification Shown.');
*
* setTimeout(function hideNotification() {
* console.log('Hiding notification....');
* hide(); //manually close the notification (you can skip this if you use the autoClose option)
* }, 5000);
* }
* });
* });
*
* //service worker example
* navigator.serviceWorker.register('service-worker.js').then(function(registration) {
* document.querySelector('.some-button').addEventListener('click', function onClick() {
* webNotification.showNotification('Example Notification', {
* serviceWorkerRegistration: registration,
* body: 'Notification Text...',
* icon: 'my-icon.ico',
* actions: [
* {
* action: 'Start',
* title: 'Start'
* },
* {
* action: 'Stop',
* title: 'Stop'
* }
* ],
* autoClose: 4000 //auto close the notification after 4 seconds (you can manually close it via hide function)
* }, function onShow(error, hide) {
* if (error) {
* window.alert('Unable to show notification: ' + error.message);
* } else {
* console.log('Notification Shown.');
*
* setTimeout(function hideNotification() {
* console.log('Hiding notification....');
* hide(); //manually close the notification (you can skip this if you use the autoClose option)
* }, 5000);
* }
* });
* });
* });
* ```
*/
webNotification.showNotification = function () {
//convert to array to enable modifications
const argumentsArray = Array.prototype.slice.call(arguments, 0);
if ((argumentsArray.length >= 1) && (argumentsArray.length <= 3)) {
const data = parseInput(argumentsArray);
//get values
const callback = data.callback;
const title = data.title;
const options = data.options;
webNotification.requestPermission(function onRequestDone(granted) {
if (granted) {
createAndDisplayNotification(title, options, callback);
} else {
callback(new Error('Notifications are not enabled.'), null);
}
});
}
};
return webNotification;
}));