The Web Notifications API

While often annoying and unwanted, notifications can play a vital role in our usage of the web. Thankfully, the Web Notifications API offers a way to integrate directly with native notification systems, while respecting user and operating system preferences. Let's jump right in.

Checking compatibility is an important step when using Web APIs. It typically consists of checking for an object key on the window global using the JavaScript in operator. For this particular demo, it looks something like this:

if ('Notification' in window) {
  // do stuff

Next, we need to request permission from the user. Requesting permission is a workflow that's built right into the browser so many of you will have encountered it already, usually manifesting in a pop-up near the address bar. Currently, Firefox and Safari require that this request is triggered as the result of a direct user action, not just on page load, preventing websites from spamming users with notification requests they did not want.

let permission = await Notification.requestPermission()
Note: the await based syntax is not supported in Safari 🙄

This function call returns either 'default', 'denied', or 'granted'. If the user grants permission, sending a notification is as easy as constructing it!

if (permission === 'granted') {
  new Notification("Some title here!", { options })

You can explore all the different options in the MDN docs linked below, but here are two that I found interesting:

A vibration pattern for the device's vibration hardware to emit with the notification.
An array of NotificationActions that represent custom actions a user can take on a certain notification

I encourage you to pop open the browser developer tools and try constructing Notification objects to get familiar with the options.

Thanks for joining me for the first edition of Perusing the Platform. If you are interested in any of the source, feel free to check your browser developer tools for pristine, unmodified HTML, CSS, and JS :)