JSFiddle - React, Tailwind, and code Playground

by Vignesh Gopalakrishnan

JavaScript

function subscribeUser() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then((registration) => {
        if (!registration.pushManager) {
          // Push manager unavailable.
          return;
        }
        registration.pushManager.getSubscription().then((existedSubscription) => {
          if (existedSubscription === null) {
            // 'No subscription detected, make a request.

            registration.pushManager.subscribe({
              applicationServerKey: convertedVapidKey,
              userVisibleOnly: true,
            }).then((newSubscription) => {
              // New subscription added
              sendSubscription(newSubscription);
            }).catch((e) => {
              console.error(e);
              if (Notification.permission !== 'granted') {
                // Permission was not granted.
              } else {
                // 'An error ocurred during the subscription process
              }
            });
          } else {
            // Existed subscription detected
            sendSubscription(existedSubscription);
          }
        });
      })
      .catch((e) => {
        console.error('An error ocurred during Service Worker registration.', e);
      });
  }
}

const sendSubscription = (sub) => {
  console.log(sub)
}