Introduction to Push Notifications

Introduction to Push Notifications

Pulling your web app one step closer to native apps
Ferenc Almasi β€’ Last updated 2021 November 11 β€’ Read time 6 min read
Get your weekly dose of webtips
  • twitter
  • facebook

Push Notifications are a great way to stay in touch with your userbase. It takes your web app one step closer to native desktop and mobile apps.

These notifications can be triggered either by your running app or even from your server when your app is not running. The API requires the user’s permission so you can be sure you only send notification to those who really want them.

They are working on top of a Service Worker, a special type of web worker whose purpose is to make your app usable when users are offline. So in order to use push notifications, you have to have a service worker in place. After establishing a service worker we can go ahead and check for support and user permission.


Checking Support and Permission

If we check support on Caniuse, we can see that the notification API is not yet widely adopted, it’s currently sitting at 78%.

Support on caniuse

This is why we need to check whether the browser supports it. Luckily it can be done with a single if statement:

Copied to clipboard!
if ('Notification' in window && navigator.serviceWorker) {
    // This means we can send notifications
}
notification.js

As you can see, we also need to check for the presence of serviceWorker since notifications are sent through them. Apart from support, we also need to check for permission, since we need to get user permissions to show notifications:

Copied to clipboard! Playground
if (Notification.permission === 'granted') {
    // user has already granted access to the Notification API
    // this means we can send notifications
} else if (Notification.permission === 'blocked') {
    // the user has denied the use of push notifications
    // we can fall-back to an only browser implementation
} else {
    // permissions has not been given yet
    // we can show a prompt to the user
    Notification.requestPermission(permission => {
        if (permission === 'granted') {
            // push the first notification
        }
    });
}
notification.js

If the first if statements have been fulfilled, we can start sending notification to the users.


Sending Notifications

As mentioned at the beginning of this article, to send notifications we have to have a serviceWorker registered. To show notifications, we will need to use the service worker registration object:

Copied to clipboard! Playground
// First we need to register a service worker
navigator.serviceWorker.register('sw.js');

// We can use serviceWorker.ready.then to wait until the registration has been done.
navigator.serviceWorker.ready.then(() => {
    if ('Notification' in window && navigator.serviceWorker) {
        Notification.requestPermission(permission => {
            if (permission == 'granted') {
                // Using the registration object, we can call the `showNotification` method to push notification
                navigator.serviceWorker.getRegistration().then(registration => {
                    registration.showNotification('πŸ‘‹ sent from push notification');
                });
            }
        });
    }
});
notification.js

After registration and checking for support/permission, we can call serviceWorker.getRegistration() to request the registration object from the service worker, then we can send out our very first push notification:

sending push notification
Make sure you test it with a webserver

Looks good but nothing fancy so far. Let’s add some more options.

Adding More Options

For adding options, you can create a new object and add it as a second parameter to showNotification:

Copied to clipboard! Playground
navigator.serviceWorker.getRegistration().then(registration => {
    const options = {
        body: 'This notification is brough to you by a `serviceWorker`',
        icon: 'icon.png',
        silent: true
    };

    registration.showNotification('🍊 Your daily notification', options);
});
notification.js

In this case, the first parameter becomes the title. For a full list of available options, please see the documentation on MDN. There are plenty of useful properties you can pass, such as:

  • vibrate: the vibration pattern used for mobile devices
  • silent: a boolean specifying whether the notification is silent or not
  • data: an arbitrary data containing any value so that you can identify which notification was interacted with
  • actions: an array of NotificationActions available for the user to choose from, which we will look into right now
push notification sent with additional options
Push notification with the provided options

Adding Actions

If you want the user to interact with your push notification you need to add an actions object to your options. Adding the following object will add two new buttons to the notification:

Copied to clipboard!
actions: [
    { action: 'open',  title: 'Open',  icon: 'open.png' },
    { action: 'close', title: 'Close', icon: 'close.png' },
]
notification.js

There are three properties you can use here:

  • action: used for identifying the action the user takes
  • title: this will be the text on the button
  • icon: in case there’s not enough space for the title, an icon will be displayed instead
Adding buttons to push notifications
Buttons on push notification

Listening for Events

The last thing to do is to listen when the user clicks one of the buttons so we can take action accordingly. For that, you need to attach an event listener inside the Service Worker:

Copied to clipboard!
self.addEventListener('notificationclick', event => {
    console.log(event);
});
sw.js

Adding the above lines into sw.js (the service worker which we have registered) will log out the emitted event:

Notification event object

Inside the NotificationEvent, you have access to the action which can tell us which button was clicked by the user.

Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScriptinfo Remove ads

Summary

Now you can send notifications to users whenever it is suitable. It’s a great way to keep in touch with your users, increase engagement, and deliver updates right into their devices. Users can opt-in and out-out any time and the number of options you can provide for your notifications can make your content rich as well as tailored to your users.

Now comes the hard part: making good business decisions and figuring out the what, when, and how. What you should notify users about, when is the right time to notify them (don’t do it in the middle of the night) and how frequent your notifications should be. The answers to these questions will differ for each application so the best way is to start experimenting right now.

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.