Day 2- Push notification. Push!

Day 2- Push notification. Push!

Whew!

Time to make the service worker.... work

So, for an Arabic learning platform that offers subscription based services to users, nothing makes it more amazing than occasional discount offers.

Users mightn't be keen to check their email every now and then for these promotions so, Hello push notifications.

How'd it go?

urgh.. Some hurdles here and there, but here we are.

Now let me take you through it

1. I created the push notification button in my markup

After adding the button element to my markup, I went ahead to declare it in index.js using query selector.

See snippet below

html
<button id="notif" class="btn btn-success mb-3">
Push Notifications</button>

index.js
const push = document.querySelector("#notif");

2. Next is to confirm if the user's browser supports notifications

If the user's browser supports notifications, event listener runs a function notifyUser once the user clicks the push notification button.

See snippet below

if ("Notification" in window) {
    push.style.display = "block";
    push.addEventListener("click", notifyUser);
  }

3. The notifyUser function

Here, the user gets alerted if notification isn't enabled on his/her browser, else, the function notificationCard will run.

Also, console logs the user's choice (granted or rejected).

See snippet below

const notifyUser = () => {
    Notification.requestPermission((result) => {
      console.log("user choice", result);
      if (result !== "granted") {
        alert("Kindly enable notification");
      } else {
        notificationCard();
      }
    });
  };

4. Now, it's time to write the notificationCard function

Here, the notification API takes in an object I've named card, which displays when the user grants access to push notifications.

const notificationCard = () => {
    if ("serviceWorker" in navigator) {
      let options = {
        body: "You will now receive notifications!",
        icon: "./images/navbar-brand.png",
        image: "./images/navbar-brand.png",
        dir: "ltr",
        tag: "confirm-notification",
        renotify: true,
        actions: [
          { action: "confirm", title: "Okay", icon: "./images/navbar-brand.png" },
          { action: "cancel", title: "Cancel", icon: "./images/navbar-brand.png" },
        ],
      }; 

      navigator.serviceWorker.ready.then((swreg) => {
        swreg.showNotification("Successful!);
      });
    }
  };

5 Finally, an additional event listener in the service worker script

This listens for a click on the notification button. If the user grants access i.e confirm, console logs access granted, else, console logs access not granted.

See snippet below

const notificationCard = () => {
    if ("serviceWorker" in navigator) {
      let options = {
        body: "You will now receive notifications!",
        icon: "./images/navbar-brand.png",
        image: "./images/navbar-brand.png",
        dir: "ltr",
        tag: "confirm-notification",
        renotify: true,
        actions: [
          { action: "confirm", title: "Okay", icon: "./images/navbar-brand.png" },
          { action: "cancel", title: "Cancel", icon: "./images/navbar-brand.png" },
        ],
      }; 

      navigator.serviceWorker.ready.then((swreg) => {
        swreg.showNotification("Successful!);
      });
    }
  };

One last thing

For best practices and performance sake (due to syntax, scope and all), the code (asides the additional listener in index.sw.js) is arranged (in index.js) as seen in the snippet below

const notificationCard = () => {
    if ("serviceWorker" in navigator) {
      let options = {
        body: "You will now receive notifications!",
        icon: "./images/navbar-brand.png",
        image: "./images/navbar-brand.png",
        dir: "ltr",
        tag: "confirm-notification",
        renotify: true,
        actions: [
          { action: "confirm", title: "Okay", icon: "./images/navbar-brand.png" },
          { action: "cancel", title: "Cancel", icon: "./images/navbar-brand.png" },
        ],
      }; 

      navigator.serviceWorker.ready.then((swreg) => {
        swreg.showNotification("Successful!);
      });
    }
  };


 const notifyUser = () => {
    Notification.requestPermission((result) => {
      console.log("user choice", result);
      if (result !== "granted") {
        alert("Kindly enable notification");
      } else {
        notificationCard();
      }
    });
  };

if ("Notification" in window) {
    push.style.display = "block";
    push.addEventListener("click", notifyUser);
  }

That's it!

Let me know if I did a good job explaining here will ya?

Thanks for reading! Till tomorrow then.