blob: 9a1598efced0f4969d43dcb1543a5a0e3340e020 [file] [log] [blame]
Matteo Scandolob585d382016-06-15 14:53:33 -07001/* eslint-disable angular/ng_window_service*/
Matteo Scandolo1a5bf202016-05-31 14:26:26 -07002(function() {
3 'use strict';
4
Matteo Scandolo1a5bf202016-05-31 14:26:26 -07005 angular
6 .module('xos.helpers')
7 .factory('Notification', function(){
8 return window.Notification;
9 })
10 /**
11 * @ngdoc service
12 * @name xos.helpers.xosNotification
13 * @description This factory define a set of helper function to trigger desktop notification
14 **/
15 .service('xosNotification', function($q, $log, Notification) {
16
17 this.checkPermission = () => {
18 const deferred = $q.defer();
19 Notification.requestPermission()
20 .then(permission => {
21 if (permission === 'granted') {
22 deferred.resolve(permission);
23 }
24 else {
25 deferred.reject(permission);
26 }
27 });
28 return deferred.promise;
29 };
30
31 this.sendNotification = (title, options) => {
32 const notification = new Notification(title, options);
33 notification.onerror = function(err){
34 $log.error(err);
35 };
36 };
37
38 /**
39 * @ngdoc method
40 * @name xos.helpers.xosNotification#notify
41 * @methodOf xos.helpers.xosNotification
42 * @description
43 * This method will check for user permission and if granted will send a browser notification.
44 * @param {string} title The notification title
45 * @param {object} options The notification options: `{icon: 'url', body: 'Notification body'}`
46 **/
47
48 this.notify = (title, options) => {
49 if (!('Notification' in window)) {
50 $log.info('This browser does not support desktop notification');
51 }
52 else if (Notification.permission !== 'granted') {
53 this.checkPermission()
54 .then(() => this.sendNotification(title, options));
55 }
56 else if (Notification.permission === 'granted') {
57 this.sendNotification(title, options);
58 }
59 }
60
61 })
62})();