Push Notifications

Part 1 - Getting Started with Web Push Notifications Service Workers

Sanjeev Kumar
April 16, 2024
Discover web push notifications service workers basics, create a project structure, and confirm browser support. Move onto Part 2 for user permissions & subscriptions.
TABLE OF CONTENTS

Web push notifications have become increasingly popular as an efficient way to reach users, foster meaningful connections, and promote timely interaction. This article introduces the fundamentals of web push notifications and sets up a basic project structure for implementing them.

Read all parts of this push notification service workers series here:

  1. Part 1 - Getting Started with Web Push Notifications Service Workers
  2. Part 2 - Obtaining User Permissions and Managing Subscriptions for Web Push Notifications
  3. Part 3: Crafting Dynamic and Feature-Rich Push Notifications

Basics of Push Notifications:

Push notifications are messages displayed to users outside the context of a web page or application. Unlike traditional notifications triggered by user actions, push notifications originate from external sources, typically served by dedicated servers. Two main types of push notifications are local and push notifications.

Difference Between Local and Push Notifications:

  • Local notifications are initiated by the web application itself, often driven by user activities or periodic reminders. For instance, alarms, reminders, or updates about recent actions taken within the application.
  • Push notifications stem from external triggers, usually managed by a dedicated server infrastructure. Common examples include news updates, incoming messages, or event invitations.

Components Overview:

Three core components facilitate push notifications in modern web browsers:

  1. Service Workers: Background scripts executing separately from the web page, responsible for intercepting and processing incoming requests, maintaining state, and performing tasks independently of user interactions.
  2. Notification API: Provides a declarative interface for displaying system notifications, supporting customizable appearances, actions, and behaviors.
  3. Push API: Connects web applications to push services, enabling bi-directional communication channels for exchanging data between client-side and server-side components.

Basic Project Structure and Boilerplate Code:

Create a new project folder and initialize it with Git:

        
            $ mkdir push-notifications && cd push-notifications
            $ git init
        
    

Structure the project as follows:

        
            - push-notifications/
            |-- index.html
            |-- index.css
            |-- index.js
            |-- service-worker.js
        
    

Include the following boilerplate code in the respective files:

index.html:

        
          <!doctype html>
          <html lang="en">
          <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Push Notifications Tutorial</title>
            
            <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
          </head>
          <body>
            <div class="container mt-5">
              <h1>Push Notifications Tutorial</h1>
              <button id="notifyButton" class="btn btn-primary my-3">Notify Me!</button>
            </div>
            
            <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSGFpoO/ufreqqF6MVu4JdG7PhIxZlW8sSJv43gkdSHlua9DmM/" crossorigin="anonymous"></script>
            <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.16.6/dist/umd/popper.min.js" integrity="sha384-VsqY1/z4Evsnh3F6UdgjaLcccy7x/rvvy4tphMNRTlu9+aJ0D3MbmWnyj/HBLpdQ" crossorigin="anonymous"></script>
            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
            
            <script src="index.js"></script>
          </body>
          </html>
        
    


index.js:

        
            document.getElementById('notifyButton').addEventListener('click', () => {
              // Handle the 'click' event here
            });
        
    


service-worker.js:

// Handle service worker lifecycle events and push notifications here

Verifying Browser Support:

It's crucial to validate that the user's browser supports the required technologies, mainly Service Workers and the Push API. Introduce the following helper functions in the index.js file:

        
            const checkBrowserSupport = () => {
              if ('serviceWorker' in navigator) {
                console.info('Service Workers are supported.');
              } else {
                console.warn('Service Workers are not supported.');
              }

              if ('PushManager' in window) {
                console.info('Push API is supported.');
              } else {
                console.warn('Push API is not supported.');
              }
            };

            checkBrowserSupport();
            ```vbnet

            Finally, invoke the `checkBrowserSupport` function in the `index.js` script:

            ```javascript
            document.addEventListener('DOMContentLoaded', () => {
              checkBrowserSupport();
            });

        
    


Load the index.html file in a modern browser such as Google Chrome, Mozilla Firefox, Microsoft Edge, or Apple Safari to observe the logged messages indicating the availability of the required components.

Conclusion:

In this article, we learned the fundamentals of web push notifications, explored the differences between local and push notifications, and established a basic project structure with boilerplate code. Furthermore, we verified browser support for the underlying technologies. In the next article, we will dive deeper into requesting user permissions, distinguishing permission states, managing subscriptions, and sharing debugging tips for Service Workers.

Read all parts of this push notification service workers series here:

  1. Part 1 - Getting Started with Web Push Notifications Service Workers
  2. Part 2 - Obtaining User Permissions and Managing Subscriptions for Web Push Notifications
  3. Part 3: Crafting Dynamic and Feature-Rich Push Notifications
Written by:
Sanjeev Kumar
Engineering, SuprSend
Get a powerful notification engine with SuprSend
Build smart notifications across channels in minutes with a single API and frontend components
Implement a powerful stack for your notifications
By clicking “Accept All Cookies”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. View our Privacy Policy for more information.