myHotTake

Tag: web push guide

  • How Does the Push API Function in JavaScript?

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


    I’m running a little antique shop at the end of a charming village lane. The Push API is like hiring a town crier to stand outside my shop and announce new arrivals to everyone who passes by. It’s an exciting concept because it means potential customers don’t have to constantly pop in to check if anything new has arrived—they’ll hear about it as soon as it happens.

    However, there are some limitations to this setup. First, not everyone in the village might be around to hear the announcements. Some villagers are out in the fields or visiting other towns. Similarly, in the digital world, not all devices support the Push API equally, so some people might miss these notifications.

    Another challenge is that my town crier has a limited range and can’t travel too far. This means that only those nearby will hear the announcements. In the same vein, the Push API is limited by network connectivity and browser support, so it’s not always effective in reaching everyone everywhere.

    Moreover, if my crier goes on and on about every tiny detail, villagers might get annoyed by the constant noise. In the digital realm, users can become overwhelmed by too many notifications, leading them to mute or block them entirely.

    Lastly, there’s a cost to keeping a town crier employed. In tech terms, this translates to the need for maintaining a reliable server and handling the complexities of managing subscriptions and security, which can be resource-intensive.

    In essence, while the Push API offers a convenient way to keep people informed, just like my town crier, it requires careful management to ensure its messages are both heard and appreciated.


    Back in my antique shop, the town crier (Push API) needs instructions on what to announce and when. In JavaScript, this is like setting up the Push API to send notifications to users. Let’s say I want the crier to announce whenever a new shipment arrives. In JavaScript, I would start by registering a service worker, which acts like the crier’s script.

    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.error('Service Worker registration failed:', error);
        });
    }

    Next, I need to make sure the crier knows whom to notify. In JavaScript, this means subscribing the user to push notifications.

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

    Once the subscription is set up, I can send notifications whenever there’s news in the shop. For this, I need to send a push message from my server, like sending a letter to the crier with the latest update.

    function sendPushNotification(subscription, payload) {
      fetch('/send-notification', {
        method: 'POST',
        body: JSON.stringify({ subscription, payload }),
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(function(response) {
        if (!response.ok) {
          throw new Error('Failed to send notification');
        }
        return response.json();
      }).then(function(data) {
        console.log('Push notification sent:', data);
      }).catch(function(error) {
        console.error('Error sending push notification:', error);
      });
    }

    Key Takeaways:

    1. Service Worker: Acts as the backbone of the Push API, enabling background scripts for handling push events.
    2. Subscription: Allows users to opt-in for receiving notifications, similar to villagers agreeing to listen to the town crier.
    3. Notification Management: Requires careful handling to ensure messages are relevant and not overwhelming, akin to balancing the volume and frequency of the crier’s announcements.
    4. Resource Considerations: Managing subscriptions and notifications can be resource-intensive and needs careful planning, much like the logistics of running an effective announcement system.