It took me a while of looking around StackOverflow and such to find out how to send browser notifications, but it turns out to be really simple. What I'm going to do here is walk you through a tutorial on making a simple notification-sending function.
At first, when the function is called, it will have to ask for permission first, but after that, it will be able to send all sorts of notifications.
Let's get started!!
First, let's create the function. It'll have three parameters. One for the title, next for the message, and the last for the icon.
function sendNotif(title, text, icon){
}
Next, just to be safe, let's make sure the browser supports notifications.
if (!("Notification" in window)) {
console.warn("Your Browser does not support Chrome Notifications :(")
}
Let's chain onto the if statement with an else if
. This statement tests if the notification status is granted or not. If it is granted, it will send a notification.
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
let notif = new Notification(title, {
icon: icon,
body: text
});
}
Still, we'll chain onto the else-if statement. Let's add another one. This statement will request permission if it isn't granted or denied.
else if (Notification.permission !== 'denied') {
//request notification permission
Notification.requestPermission((perm) => {
//save permission status
if (!('permission' in Notification)) {
Notification.permission = perm;
}
//if granted, send a notification immediately
if (perm === "granted") {
let notif = new Notification(title, {
icon: icon,
body: text
});
}
});
}
And that should be it. Your function should be working well. Let's, for extra error handling, add an else statement at the end of the chain and log the current notification to the console if it isn't denied or allowed.
else {
console.warn(`Failed, Notification Permission is ${Notification.permission}`);
}
Have fun and don't spam websites or users with notifications.
Happy Coding.
Top comments (7)
In 4th code block shouldn't second
if
haveperm
instead ofpermission
variable?Nevertheless simple and easy to understand article. Thanks 👍
Could you add/explain more options that we can specify in options?
Whoops I think I made that little mistake there. Thanks for letting me know.
developer.mozilla.org/en-US/docs/W...
ps: an advice to make reading more interactive is to add links to different api and resources!
Nice !!
thanks. Well, actually, thanks to stackOverflow ;)
Well do you remember me?
I am abhijitbiswas07 on KA :D
LEVIATHAN YOU ARE ON DEV.TO WOAH
also saving the article for later thanks