Last active
March 15, 2018 12:34
-
-
Save vldvel/c43a49d1f3162cd3f794a775c966b85b to your computer and use it in GitHub Desktop.
Notification API
This file contains hidden or 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 createNotification () { | |
// first let's check browser support | |
if (!('Notification' in window)) { | |
throw new Error('Browser doesn\'t support notifications'); | |
} | |
// now let's look whether permission is already granted or not | |
switch (Notification.permission) { | |
case 'granted': { | |
return innerCreateNotification; | |
} | |
case 'denied': { | |
alert('Notification already denied'); | |
break; | |
} | |
case 'default': { | |
Notification.requestPermission((permission) => { | |
if (permission === 'granted') { | |
return innerCreateNotification; | |
} | |
alert('Notification denied'); | |
}); | |
} | |
} | |
function innerCreateNotification(notificationProps) { | |
const notification = new Notification(notificationProps.title, notificationProps); | |
if (Number.isInteger(notificationProps.closeTimeout)) { | |
setTimeout(() => { | |
notification.close(); | |
}, notificationProps.closeTimeout); | |
} | |
} | |
} | |
// first - initialize so we don't have to check permission each time | |
const notificationHandler = createNotification(); | |
// options object for notification | |
const notificationProps = { | |
title: 'I\'m notification', | |
body: 'Here is my desription', | |
icon: 'https://avatars1.githubusercontent.com/u/22643415', | |
vibrate: [50, 100, 150], | |
closeTimeout: 600 | |
} | |
// create notification with options object | |
notificationHandler(notificationProps); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment