push notification with service worker

 (works only on chrome)


  <script>
    // Check if the browser supports service workers
    function urlBase64ToUint8Array(base64String) {
      const padding = '='.repeat((4 - base64String.length % 4) % 4);
      const base64 = (base64String + padding)
        .replace(/-/g, '+')
        .replace(/_/g, '/');
   
      const rawData = window.atob(base64);
      const outputArray = new Uint8Array(rawData.length);
   
      for (let i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
      }
      return outputArray;
    }

    if ('serviceWorker' in navigator) {
      // Register the service worker
      navigator.serviceWorker.register('sw.js').then(function(registration) {
        console.log('Service worker registered with scope:', registration.scope);
       
        // Ask for permission to show notifications
        const publicVapidKey = '';

        Notification.requestPermission().then(function(permission) {
          if (permission === 'granted') {
            // Get the registration token for the current user
            registration.pushManager.subscribe({
              userVisibleOnly: true,
              applicationServerKey: ''
            }).then(function(subscription) {
                // console.log(subscription)
                console.log('Push subscription:', subscription);
                console.log('p256dh key:', btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('p256dh')))));
                console.log('auth key:', btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('auth')))));
                console.log('User is subscribed with endpoint:', subscription);
                let subscription2 = {
                    keys : {
                        p256dh: btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('p256dh')))),
                        auth: btoa(String.fromCharCode.apply(null, new Uint8Array(subscription.getKey('auth')))),
                    },
                    endpoint:subscription.endpoint
                }
                 fetch('/subscribe', {
                    method: 'POST',
                    body: JSON.stringify(subscription2),
                    headers: {
                    'Content-Type': 'application/json',
                    },
        });
            }).catch(function(error) {
              console.error('Failed to subscribe the user:', error);
            });
          }
        });
      }).catch(function(error) {
        console.error('Failed to register the service worker:', error);
      });
    }
  </script>

sw.js

self.addEventListener('push', function(event) {
    console.log('[Service Worker] Push Received');
    console.log('[Service Worker] Data:', event.data.text());
 
    const title = 'Push Notifications Example';
    const options = {
      body: event.data.text(),
    //   icon: 'images/icon.png',
    //   badge: 'images/badge.png'
    };
 
    event.waitUntil(self.registration.showNotification(title, options));
  });
 
  self.addEventListener('notificationclick', function(event) {
    console.log('[Service Worker] Notification click received.');
 
    event.notification.close();
 
    event.waitUntil(clients.openWindow('https://www.example.com'));
  });
 

Comments

All time Best Post

Write a program that declares a class named Person. It should have instance variables to record name, age and salary. Use new operator to create a Person object. Set and display its instance variables.

express session login system using node express mongodb

IMAGE CRUD OPERATION USING EXPRESS MONGOOSE MULTER

connect websocket to binance api and store t he true value in the db

CRUD APP WITH SORT IN NODE EXPRESS AND MONGODB

Rock-Paper-Scissor Game in Pure JavaScript

how to delete image from the folder directly from a Request (MULTER)

calculate rsi

java program for 1 to 10 print using while loop