Skip to content
Advertisement

Service Worker onClick event – Open and pass some data to a PWA

I have implemented push notifications for my PWA and my service worker (SW) is currently handling clicks on a notifications like this:

  1. If the app is running it will put it in the foreground and send it some data using the Client.postMessage API
  2. If the app is not running it will launch it via Client.openWindow using URL parameters that contain some minimal information about the push notification

Point 1 works just as I want. But for 2, I would like to be able to send to my app the same data as for 1, and I cannot add it to the URL (the payload is too large). The issue is that I can only use Client.postMessage when my app is ready to receive such messages…

What is the simplest way to do that?

Note: my use case is a chat app for which a push notification is displayed when a message is received and a click on the notification triggers the app and shows the corresponding chat and message. I want to pass the content of the message itself (which is in the push notification received by the service worker) to the app so it can show directly, instead of having to pull it from the backend.

Advertisement

Answer

This is how I solved the problem:

  1. SW receives a push notification and the user clicks on it
  2. SW stores the information to send to the app in IndexedDB associated with a unique id
  3. SW uses Client.openWindow with a custom URL + the unique id to open the app When the app is started, it pulls the data from IndexedDB using the id
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement