How to send Chrome / Browser Notifications

Conner Ow - Nov 16 '21 - - Dev Community

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){

}
Enter fullscreen mode Exit fullscreen mode

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 :(")
}
Enter fullscreen mode Exit fullscreen mode

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
  });
}
Enter fullscreen mode Exit fullscreen mode

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
      });
    }
  });
}
Enter fullscreen mode Exit fullscreen mode

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}`);
}
Enter fullscreen mode Exit fullscreen mode

Have fun and don't spam websites or users with notifications.
Happy Coding.

. . . . . . . . . . . . . . . . .
Terabox Video Player