Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to activate a react route and pass data from the service worker?

I have a SPA PWA React app.
It is installed and running in standalone mode on the mobile device (Android+Chrome).

Let's say the app lists people and then when you click on a person it diplays details using /person route.

Now, I'm sending push notifications from the server and receiving them in the service worker attached to the app. The notification is about a person and I want to open that person's details when the user clicks on the notification.

The question is:

  • how do I activate the /person route on my app from the service worker
  • and pass data (e.g. person id, or person object)
  • without reloading the app

From what I understand, from the service worker notificationclick event handler I can:

  • focus on the app (but how do I pass data and activate a route)
  • open an url (but /person is not a physical route, and either way - I want avoid refreshing the page)
like image 322
igorludi Avatar asked Oct 16 '22 07:10

igorludi


1 Answers

You can listen for click event for the Notification which you show to the user. And in the handler, you can open the URL for the corresponding person which comes from your server with push event.

notification.onclick = function(event) {
  event.preventDefault(); 

  // suppose you have an url property in the data
  if (event.notification.data.url) {

      self.clients.openWindow(event.notification.data.url);
  }
}

Check these links:

  • https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/notificationclick_event
  • https://developer.mozilla.org/en-US/docs/Web/API/Clients/openWindow
like image 53
Dmytro Olefyrenko Avatar answered Oct 21 '22 05:10

Dmytro Olefyrenko