Exploring Notifications

I was recently working on a Pomodoro Timer and decided it would be a great time to look into browser notifications. I discovered the Notifications API and started to play around with how to incorporate it into my timer.

The first step is to request permission from the user to allow notifications. A callback function may be specified that is called once the user responds to the request. I created a function that alerts the user if they deny the request.

Notification.requestPermission().then(function(result){
  if(result === "denied"){
    alert("You will not receive alerts for the timer");
  }
});

Now that we’ve requested permission, the next step is to actually create a notification. I decided to do one that triggers on button click. All you have to do is specify a title in the Notification constructor.

var notification = new Notification("Hey look, a notification!");

Awesome, now we’ve got a working notification! But wait, how does this work across browsers? Lucky for us, the Notifications API has basic support for most browsers. However, in order to make sure the rest of the code executes fully in all browsers, we need to check if Notification exists before we request permission. All this takes is a simple if statement.

if(window.Notification && window.Notification.requestPermission()){
  Notification.requestPermission().then(function(result){
    if(result === "denied"){
      alert("You will not receive alerts for the timer");
    }
  });
}

And that’s it! Check out my working Codepen example here.