myHotTake

Tag: push notifications

  • How Do Service Workers Handle Push Notifications?

    If you find this story helpful, feel free to give it a like or share it with others who might enjoy it too!


    I’m the night watchman at a hotel. My job is to ensure that all the guests get their important messages, no matter the hour. The hotel is like a web application, constantly buzzing with activity, and I, the night watchman, am akin to the Service Worker in JavaScript.

    Each night, as the guests sleep, I stand vigilant in the lobby, ready to deliver any urgent telegrams that might come in. These telegrams are like push notifications, carrying vital information from the outside world. Just like a Service Worker operates in the background, independent of the web page, I work when the guests aren’t actively engaging with the hotel’s services.

    When a telegram arrives, I don’t just barge into the guests’ rooms unannounced. I’ve got a special protocol to follow: I first determine the recipient by checking the room number, much like how a Service Worker listens for the ‘push’ event to ensure the notification is intended for the right web app. Once I’ve confirmed the recipient, I gently slip the telegram under the door, ensuring it’s noticed without causing a disturbance. This is similar to how I would use the Service Worker’s self.registration.showNotification() method to display a notification to the user.

    Sometimes, guests might want to respond to these messages, just as users might click on a notification to take action. I’m prepared for this too, ready to facilitate communication or provide further assistance, just like a Service Worker can handle ‘notificationclick’ events to perform actions like opening a specific page of the web app.

    And so, night after night, I continue my silent vigil, ensuring that no important telegram goes undelivered and every guest is kept informed, much like how a Service Worker diligently manages push notifications behind the scenes, enhancing the user experience without ever being directly seen.


    First, to set the stage for handling push notifications, I need to register a Service Worker in my web application. This is like hiring the night watchman:

    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('/service-worker.js').then(registration => {
        console.log('Service Worker registered with scope:', registration.scope);
      }).catch(error => {
        console.error('Service Worker registration failed:', error);
      });
    }

    Now, in the service-worker.js file, I, the watchman, wait for push events, ready to deliver notifications:

    self.addEventListener('push', event => {
      const data = event.data ? event.data.json() : {};
      const title = data.title || 'No title';
      const options = {
        body: data.body || 'No body content',
        icon: data.icon || '/default-icon.png',
        badge: data.badge || '/default-badge.png'
      };
    
      event.waitUntil(
        self.registration.showNotification(title, options)
      );
    });

    When a push notification arrives, I check the contents (like determining the recipient and content of a telegram) and use showNotification to deliver the message. This is akin to slipping the telegram under the guest’s door.

    Additionally, I handle interactions with these notifications, such as when a guest responds to a telegram:

    self.addEventListener('notificationclick', event => {
      event.notification.close(); // Close the notification
    
      event.waitUntil(
        clients.matchAll({ type: 'window', includeUncontrolled: true }).then(clientList => {
          if (clientList.length > 0) {
            let client = clientList[0];
            return client.focus();
          }
          return clients.openWindow('/');
        })
      );
    });

    Here, when a user clicks on a notification, I (the night watchman) ensure they are directed to the appropriate page in the application, similar to guiding a guest to the hotel’s front desk for more information.

    Key Takeaways:

    • Service Workers act like a vigilant watchman, operating behind the scenes to manage push notifications and other background tasks.
    • Push Notifications are handled through the ‘push’ event, where we can customize the notification content and display it using showNotification.
    • User Interaction with notifications is managed by listening for ‘notificationclick’ events, allowing for seamless transitions back to the web application.
  • How Do Servers Send Push Notifications? A Simple Guide

    If you find this story helpful, feel free to like or share it with others who might enjoy it!


    I’m a competitive swimming coach at a big swim meet. My job is to guide my swimmers to victory by sending them signals during the race. These signals are like push notifications from a server to a user’s device. Just like I stand at the edge of the pool, the server stands ready to communicate with devices.

    Now, picture my whistle as the server’s communication tool. Every time I blow the whistle, it’s like sending a push notification. This whistle is not just any whistle; it’s special, tuned to the specific frequency that only my swimmers can hear. This is akin to the server needing permission from the user’s device to send push notifications—like obtaining a special key or token.

    Before the race, my swimmers have to put on wristbands that vibrate when they receive the whistle’s signal. This is similar to a device subscribing to receive notifications, where the swimmer (device) agrees to listen for my signals (notifications) by wearing the wristband.

    As the race begins, I keep an eye on each swimmer. If one of them is falling behind, I blow the whistle in a unique pattern to signal them to speed up. In the digital world, this would be the server sending a notification to prompt the user to take action, like checking a new message or updating an app.

    Sometimes, I see a swimmer who is right on track, so I don’t need to send any signals. Similarly, a server doesn’t spam devices with unnecessary notifications. It’s all about timing and relevance—sending the right message at the right moment.

    As the race concludes, my swimmers know to remove their wristbands, just as users can choose to unsubscribe from notifications. They’ve completed their race, and my role as the signaling coach comes to a pause until the next event.

    And just like that, sending a push notification from a server is all about permission, precise signaling, and ensuring the message is received and acted upon at the right time. If you enjoyed this analogy and found it helpful, consider liking or sharing it with others who might benefit!


    Setting Up the Whistle: JavaScript Code

    First, we need to set up the environment, much like preparing our whistle. This involves configuring the server to send notifications. In JavaScript, we might use Node.js with a library like web-push to send notifications to the browser.

    Here’s a basic example of how the server (our coach) can send a notification:

    const webPush = require('web-push');
    
    // Configure web-push library
    webPush.setVapidDetails(
      'mailto:[email protected]',
      'PUBLIC_VAPID_KEY',
      'PRIVATE_VAPID_KEY'
    );
    
    // Subscription object representing the swimmer
    const subscription = {
      endpoint: 'https://fcm.googleapis.com/fcm/send/...',
      keys: {
        p256dh: 'PUBLIC_KEY',
        auth: 'AUTH_KEY'
      }
    };
    
    // Payload to be sent
    const payload = JSON.stringify({ title: 'Swim Faster!', message: 'You are falling behind!' });
    
    // Send the notification
    webPush.sendNotification(subscription, payload)
      .then(response => console.log('Notification sent successfully:', response))
      .catch(error => console.error('Error sending notification:', error));

    Receiving the Signal: Frontend JavaScript

    On the swimmer’s side (the user’s browser), we need to ensure the swimmer is listening for the whistle. This involves registering a service worker that can handle incoming notifications.

    // Register the service worker
    navigator.serviceWorker.register('/sw.js')
      .then(registration => {
        console.log('Service Worker registered with scope:', registration.scope);
      })
      .catch(error => {
        console.error('Service Worker registration failed:', error);
      });
    
    // Subscribe to push notifications
    navigator.serviceWorker.ready.then(registration => {
      return registration.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: 'PUBLIC_VAPID_KEY'
      });
    }).then(subscription => {
      console.log('User is subscribed:', subscription);
    }).catch(error => {
      console.error('Failed to subscribe the user:', error);
    });

    Key Takeaways

    • Permission is Key: Just as swimmers need to agree to wear wristbands, devices must consent to receive notifications by subscribing.
    • Precise Signaling: Notifications should be relevant and timely, like the coach’s whistle signals during the race.
    • JavaScript Tools: Libraries like web-push in Node.js help send notifications, while service workers on the frontend listen for and display them.
    • Security: Always use VAPID keys and secure endpoints to ensure the integrity and security of your notifications.
  • How Do Service Workers Power Push Notifications?

    If you enjoy this kind of storytelling, feel free to give it a like or share it with someone who might appreciate a fresh perspective!


    I’m a competitive swimmer, and my goal is to stay ahead of the game by being the first to know when the pool is open for a surprise practice session. Just like in swimming, where preparation and timing are everything, setting up a service worker for push notifications is about getting the right message at the right time.

    First, I need a reliable coach—my service worker—who will always keep an eye on the pool schedule. The service worker is like that coach who doesn’t swim with me but stands poolside, always ready to give me the heads up. This coach is installed once, and they stay there, even when I’m not actively swimming or even at the pool.

    To get this setup, I first register my coach. I go over to the pool’s management system and say, “Hey, I want my coach to be notified immediately if there’s an update.” The registration is like a handshake with the system, ensuring my coach gets the necessary permissions to access the schedule.

    Once registered, my coach needs to subscribe to the notifications. This is akin to signing up for alerts from the pool’s management system, specifying exactly what kind of updates they should send. It’s like telling the coach, “Only let me know if the pool opens unexpectedly for practice.”

    Then comes the crucial part: the pool sends out a notification. It’s as if the management system sends a special signal to my coach, alerting them that the pool is open for practice. My coach’s job is to receive this signal and immediately pass it on to me, even if I’m not at the pool or thinking about swimming.

    So here I am, maybe at home or school, and suddenly I get a message: “Hey, practice is open now!” It’s my coach, the service worker, doing their job perfectly—ensuring I’m always in the loop and can dive into action whenever necessary.

    In this swimming analogy, the service worker is my vigilant coach, the notifications are the signals from the management, and the pool’s surprise openings are the opportunities I don’t want to miss. Together, we stay ahead, ready to jump in whenever the moment arises. Just like in swimming, it’s all about having the right setup and the right signals to stay competitive and informed.


    Setting Up the Service Worker

    In our swimming world, the first step was registering our coach. In JavaScript, this is like registering the service worker. We do this in our main JavaScript file:

    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('/service-worker.js')
        .then(function(registration) {
          console.log('Service Worker registered with scope:', registration.scope);
        })
        .catch(function(error) {
          console.log('Service Worker registration failed:', error);
        });
    }

    Here, I’m asking the browser to register my service worker using the service-worker.js script. If successful, it’s like shaking hands with the pool management, ensuring my coach is in place.

    Subscribing to Push Notifications

    Next, I need my coach to subscribe to the pool’s notifications. This involves using the PushManager to handle push subscriptions:

    navigator.serviceWorker.ready.then(function(registration) {
      return registration.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array('<Your-VAPID-Public-Key>')
      });
    }).then(function(subscription) {
      console.log('User is subscribed:', subscription);
    }).catch(function(error) {
      console.log('Failed to subscribe the user:', error);
    });

    In this code, I ensure my service worker (coach) is ready and then subscribe to notifications. The applicationServerKey is like the unique signal that tells the pool system exactly which swimmer (user) should receive alerts.

    Handling Push Events

    When the pool sends a notification, my coach needs to handle it effectively. Inside the service-worker.js file, I define how to deal with incoming push messages:

    self.addEventListener('push', function(event) {
      const options = {
        body: event.data ? event.data.text() : 'New notification!',
        icon: 'images/swimming-icon.png',
        badge: 'images/swimming-badge.png'
      };
    
      event.waitUntil(
        self.registration.showNotification('Pool Alert!', options)
      );
    });

    Here, the coach receives the signal and immediately informs me by displaying a notification. The showNotification method is like the coach shouting out, “Hey, the pool is open!”

    Key Takeaways

    1. Service Worker as a Coach: Think of the service worker as a coach who is always on standby, ready to deliver timely notifications.
    2. Registration and Subscription: Registering the service worker is like getting the coach on board, while subscribing to push notifications ensures you get the necessary alerts.
    3. Handling Notifications: Properly handling push events is crucial for receiving and acting on important updates, similar to how a coach communicates practice opportunities.
    4. Staying Informed: Just as a swimmer stays ahead by being informed of practice times, a web application keeps its users engaged with timely notifications.