Complete Notifications.js
/** | |
* A Notifications object | |
* | |
* http://caniuse.com/notifications | |
* Currently supported only in Firefox 22+, Chrome 22+, and Safari 6+ (on Mac OSX 10.8+). | |
* | |
* Note: requestPermission() MUST be called from a user gesture event in Chrome | |
* to be valid. It will fail silently otherwise! | |
* | |
* Note: Firefox and Safari will close notifications themselves | |
* if the user does nothing for a period of time. | |
* | |
* @property {boolean} supported If the current context supports Notifications or not | |
* @property {boolean} permission If the user has granted permission or not | |
* @property {function} onclick The function to be called for the 'onclick' event | |
* @property {function} onshow The function to be called for the 'onshow' or 'ondisplay' event | |
* @property {function} onerror The function to be called for the 'onerror' event | |
* @property {function} onclose The function to be called for the 'onclose' event | |
*/ | |
var Notifications = (function(self) { | |
self.supported = ("Notification" in window); | |
self.permission = false; | |
self.onclick = function() {}; | |
self.onshow = function() {}; | |
self.onerror = function() {}; | |
self.onclose = function() {}; | |
var notification = null; | |
/** | |
* Requests permission from the user to display notifications | |
*/ | |
self.requestPermission = function() { | |
if (self.supported) { | |
if (window.webkitNotifications) { | |
window.webkitNotifications.requestPermission(); | |
if (window.webkitNotifications.checkPermission() === 0) { | |
self.permission = true; | |
} | |
} else { | |
Notification.requestPermission(function(status) { | |
if (status === "granted") { | |
self.permission = true; | |
} | |
}); | |
} | |
} | |
}; | |
/** | |
* Create a notification | |
* @param {string} title The title of the notification | |
* @param {string} content The content of the notification | |
* @param {string} tag The tag of the notification | |
* @param {string} icon The icon URL of the notification | |
*/ | |
self.createNotificiation = function(title, content, tag, icon) { | |
if (self.permission) { | |
notification = new Notification(title, { | |
dir: "auto", | |
lang: "", | |
body: content, | |
tag: tag, | |
icon: icon | |
}); | |
notification.addEventListener('click', self.onclick); | |
notification.addEventListener('show', self.onshow); | |
notification.addEventListener('display', self.onshow); | |
notification.addEventListener('error', self.onerror); | |
notification.addEventListener('close', self.onclose); | |
} | |
}; | |
return self; | |
})(Notifications || {}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment