How to send Chrome / Browser Notifications
Conner Ow
Posted on November 16, 2021
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.
Posted on November 16, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 2, 2024
September 19, 2024
August 20, 2024