browser-notification
Version:
Small library built around browsers native Notification-API adding useful default behaviour.
83 lines (68 loc) • 1.84 kB
JavaScript
var settings = {
ignoreFocused: true,
timeout: 0,
cooldown: 0
};
var available = false;
var cooldownActive = false;
var focused = true;
function initNotifications(options) {
// Handle old browsers - this way we can skip polyfill Promise and Object.assign
if (!window.hasOwnProperty('Notification')) {
console.info('This browser does not support notifications');
// Mock promise always resolving to false
return {
then: function then(fn) {
return fn(false);
}
};
}
settings = Object.assign({}, settings, options);
window.onfocus = function () {
focused = true;
};
window.onblur = function () {
focused = false;
};
var availablePromise = new Promise(function (resolve, reject) {
if (Notification.permission === 'granted') {
resolve(true);
} else if (Notification.permission !== 'denied') {
Notification.requestPermission().then(function (permission) {
if (permission === 'granted') {
resolve(true);
}
resolve(false);
});
} else {
resolve(false);
}
});
availablePromise.then(function (result) {
available = result;
});
return availablePromise;
}
function notify(title, notifyOptions) {
if (!available || settings.ignoreFocused && focused || cooldownActive) {
return null;
}
var notification = new Notification(title, notifyOptions);
notification.onclick = function () {
window.focus();
notification.close();
};
if (settings.timeout !== 0) {
window.setTimeout(function () {
notification.close();
}, settings.timeout);
}
if (settings.cooldown !== 0) {
cooldownActive = true;
window.setTimeout(function () {
cooldownActive = false;
}, settings.cooldown);
}
return notification;
}
export { initNotifications, notify };