Service Worker: Node and React Js

78
July 05, 2022, at 11:40 AM

I have been able to successfully connect react.js service worker with node.js backend. Currently, I get a notification response on web app reload. But the issue i have now is making the service worker available on other backend routes or rather be able to trigger notifications from other routes if possible. Because my aim is to trigger a notification on the frontend if an action gets executed, i.e a new customer registration from a different route entirely.

Backend

index.js


app.post('/notifications/subscribe',  cors(), (req, res) => {
  const subscription = req.body
  console.log(req.body)
  const payload = JSON.stringify({
    title: 'Hello!',
    body: 'It workls.',
    url: 'https://wisdome.com',
    icon: '/images/icon.png'
  })
  webpush.sendNotification(subscription, payload)
    .then(result => console.log(result))
    .catch(e => console.log(e.stack))
  res.status(200).json({'success': true})
});

FrontEnd

subscription.js

// const convertedVapidKey = urlBase64ToUint8Array(process.env.REACT_APP_PUBLIC_VAPID_KEY)
const convertedVapidKey = urlBase64ToUint8Array('BKNikXvxR8oyiPbyr7nbN_osaWYVCEIh9aCKBiwprohNt0buZYwuOWvm6sigH474aMGmdCDXTNdFwtKK3LH5k')

function urlBase64ToUint8Array(base64String) {
  const padding = "=".repeat((4 - base64String.length % 4) % 4)
  // eslint-disable-next-line
  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
}
function sendSubscription(subscription) {
    console.log(JSON.stringify(subscription), 'sdklsoisiuweuiw')
  return fetch(`/notifications/subscribe`, {
    method: 'POST',
    body: JSON.stringify(subscription),
    headers: {
      'Content-Type': 'application/json'
    }
  })
}
export function subscribeUser() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready.then(function(registration) {
      if (!registration.pushManager) {
        console.log('Push manager unavailable.')
        return
      }
      registration.pushManager.getSubscription().then(function(existedSubscription) {
        if (existedSubscription === null) {
          console.log('No subscription detected, make a request.')
          registration.pushManager.subscribe({
            applicationServerKey: convertedVapidKey,
            userVisibleOnly: true,
          }).then(function(newSubscription) {
            console.log('New subscription added.')
            // console.log(newSubscription, 'sksmmmmmmms')
            sendSubscription(newSubscription)
          }).catch(function(e) {
            if (Notification.permission !== 'granted') {
              console.log('Permission was not granted.')
            } else {
              console.error('An error ocurred during the subscription process.', e)
            }
          })
        } else {
          console.log('Existed subscription detected.')
          // console.log(existedSubscription.endpoint, 'sksmmmmmmms')
          sendSubscription(existedSubscription)
        }
      })
    })
      .catch(function(e) {
        console.error('An error ocurred during Service Worker registration.', e)
      })
  }
}

custom-sw.js

const redirectURL = "https://www.google.com/"
self.addEventListener('push', event => {

    console.log(event.data.json(), 'sjkskj')
    const data = event.data.json()
    console.log('New notification', data)
    const options = {
      body: data.body,
      icon: data.icon,
      data: { url:data.url }, //the url which we gonna use later
      actions: [{action: "open_url", title: "Read Now"}]
    }
    event.waitUntil(
      self.registration.showNotification(data.title, options)
    );
})

self.addEventListener('notificationclick', function(event) {
  event.notification.close();
  event.waitUntil(
    // clients.openWindow(event.notification.data.url + "?notification_id=" + event.notification.data.id)
    clients.openWindow(event.notification.data.url )
    // clients.openWindow('https://www.google.com/')
    );
})

self.addEventListener(fetch, (event)=>{

  event.waitUntil(
    // this.registration.showNotification("hello", {body: 'kkkkkkk'})
  )
  if(!navigation.onLine){
    event.respondWith(
      caches.match(event.request).then((resp)={
        if(resp){
          return resp
        }
        // let requestUrl = event.request.clone()
        // fetch(reuestUrl)
      })
    )
  }
})

self.addEventListener('beforeinstallprompt', (e) => {
  // Prevent Chrome 67 and earlier from automatically showing the prompt
  e.preventDefault();
  // Stash the event so it can be triggered later.
  deferredPrompt = e;
  // Update UI to notify the user they can add to home screen
  addBtn.style.display = 'block';
  addBtn.addEventListener('click', (e) => {
    // hide our user interface that shows our A2HS button
    addBtn.style.display = 'none';
    // Show the prompt
    deferredPrompt.prompt();
    // Wait for the user to respond to the prompt
    deferredPrompt.userChoice.then((choiceResult) => {
        if (choiceResult.outcome === 'accepted') {
          console.log('User accepted the A2HS prompt');
        } else {
          console.log('User dismissed the A2HS prompt');
        }
        deferredPrompt = null;
      });
  });
});

Rent Charter Buses Company
READ ALSO
How to transform a log4j message to fit an avro schema and post to kafka

How to transform a log4j message to fit an avro schema and post to kafka

I am working on a system that sends all logs for all microservices to a single topic apache kafkaMost services are in python but we are now forwarding logs from a Streams app

107
Unable to parse input date containing abbreviated asian components using DateTimeFormatter

Unable to parse input date containing abbreviated asian components using DateTimeFormatter

I'm trying to parse a date string to LocalDate or LocalDateTime (actually any Temporal object), which contains asian abbreviated partsWhen I provide a valid abbreviated chinese component(in example below - dayOfMonth), I get DateTimeParseException

94