myHotTake

Tag: JavaScript events

  • How Does JavaScript Handle Notification Click Actions?

    If you find this story as delightful as I enjoyed crafting it, feel free to like or share it!


    I am the concierge at a hotel, and each guest that checks in hands me a unique card that tells me something about their preferences. These cards are like notification clicks in the world of JavaScript, each one signaling a specific request or action.

    Now, when a guest walks up with their card, I don’t just send them off to any random room or activity. Each card has a special code that tells me exactly where they should go. Maybe it’s a room with a sea view, a reservation at the rooftop restaurant, or a ticket to the spa. This is akin to how I handle notification clicks in JavaScript; each click carries a unique identifier that dictates its destination or action, just like the cards I receive from the guests.

    As the concierge, I have a little notebook. In it, I have detailed instructions for each possible request. If someone hands me a card for the spa, I know to call the spa to confirm the appointment and guide the guest to the elevator that takes them directly there. In JavaScript, this is like having event listeners and handlers that map each notification click to a specific function or page.

    Sometimes, guests change their minds or have special requests on the fly. Maybe someone with a reservation at the restaurant decides they want room service instead. I quickly make a note and adjust their itinerary, ensuring their experience is seamless. Similarly, in JavaScript, I can dynamically adjust the actions based on the data received from the click, ensuring flexibility and responsiveness.

    So, just like a concierge ensures each guest has a personalized and smooth experience based on their unique card, I use JavaScript to handle notification clicks, guiding users to specific pages or actions tailored to their needs. Both require attention to detail and a well-organized system to ensure everything runs without a hitch.


    In our grand hotel, imagine that each card handed to the concierge is a notification click event. Here’s how I, as the concierge, translate these clicks into specific actions using JavaScript:

    //  these are our guests' cards, each with a specific code
    const notificationClick = {
      type: 'spa', // It could be 'spa', 'restaurant', or 'room'
      data: {
        time: '2 PM', // Additional information for contextual actions
      }
    };
    
    // My notebook with instructions on how to handle each type of card
    function handleNotificationClick(event) {
      switch (event.type) {
        case 'spa':
          redirectToSpa(event.data);
          break;
        case 'restaurant':
          bookRestaurantTable(event.data);
          break;
        case 'room':
          checkRoomAvailability(event.data);
          break;
        default:
          console.log('Unknown request');
      }
    }
    
    // Instructions for each specific request
    function redirectToSpa(data) {
      console.log(`Redirecting to the spa at ${data.time}`);
      // Simulating a page redirection in a web application
      window.location.href = '/spa';
    }
    
    function bookRestaurantTable(data) {
      console.log(`Booking a table at the restaurant for ${data.time}`);
      // Simulating a page redirection
      window.location.href = '/restaurant';
    }
    
    function checkRoomAvailability(data) {
      console.log('Checking room availability');
      // Simulating a page redirection
      window.location.href = '/rooms';
    }
    
    // When a notification click event occurs, handle it
    handleNotificationClick(notificationClick);

    Key Takeaways:

    1. Event Handling: Just like the concierge uses cards to direct guests, JavaScript uses event handlers to respond to user actions. Each notification click is an event that triggers a specific function based on its type.
    2. Switch Case for Clarity: Using a switch statement helps organize and manage different types of notification clicks, ensuring each one leads to a specific action.
    3. Dynamic Redirection: Functions like redirectToSpa simulate the idea of guiding a guest to the correct destination. In a web app, this often means changing the page using window.location.href.
    4. Flexibility and Context: The event carries additional data, allowing the application to respond contextually. Just like how a card might specify the time of a spa appointment, the event’s data property provides necessary details for the action.
  • 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.