Last active
April 10, 2018 18:02
-
-
Save jeffsrepoaccount/5b9500c33b0ea50ef7ceeeb8ba9a5b4a to your computer and use it in GitHub Desktop.
Simple AngularJS service using HTML5 Notifications API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
'use strict'; | |
var module = angular.module('jrl.notifications', []); | |
module.service('notify', [ | |
'$q', '$window', | |
function($q, $window) { | |
var svc = { | |
send: function(){}, | |
requestPermission: function(){}, | |
permission: null | |
}; | |
// Let's only define stuff to do if we're inside of a | |
// context that actually supports HTML5 Notifications | |
if("Notification" in $window) { | |
svc.send = send; | |
svc.requestPermission = requestPermission; | |
} | |
return svc; | |
/** | |
* Sends a notification to the user's desktop | |
* | |
* @param string title - Title of notification | |
* @param string body - Body of notification | |
* @param string icon - Notification icon url | |
* @param string direction - One of 'ltr' or 'rtl' | |
* @return void | |
*/ | |
function send(title, body, icon, direction) { | |
direction = direction || 'ltr'; | |
if(!svc.permission) { | |
requestPermission.then(go); | |
} else if(svc.permission !== 'denied') { | |
go(); | |
} | |
function go() { | |
return new $window.Notification(title, { | |
body: body, | |
icon: icon, | |
dir: direction | |
}); | |
} | |
} | |
/** | |
* Requests permission from the user to display HTML5 notifications | |
* | |
* @return promise - Resolved only if permission is granted | |
*/ | |
function requestPermission() { | |
var defer = $q.defer(); | |
$window.Notification.requestPermission( | |
function(permission) { | |
svc.permission = permission; | |
if(permission === 'granted') { | |
defer.resolve(); | |
return; | |
} | |
defer.reject(); | |
} | |
); | |
return defer.promise; | |
} | |
} | |
]); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment