Search code examples
reactjspush-notificationnotificationsprogressive-web-appsaws-amplify

PWA Push Notification not showing when app is not running


I'm developing a Progressive Web App with React that gets notifications when a new offer has been added to the DB. Everything works fine, I open the web, asks the user to grant permissions to enable notifications, we allow them, install the PWA, run it, add a new offer in the DB, and the a notification with the new offer gets displayed (Chrome + Windows 10).

But the issue is I don't get any notifications if the PWA is not running.. I would have thought the service worker is running in the background even if the PWA is closed. What am I missing?

here is my notifyNewOffer function in my notifications.ts file

function notifyNewOffer(newOffer: Offer) {
  if ('serviceWorker' in navigator) {
    const options = {
      body: newOffer.subheading,
      icon: './logo192.png',
      image: './static/media/placeholder-offer.1bcbf040.png',
      vibrate: [100, 50, 200],
      badge: './favicon.ico',
      tag: 'new-offers',
      renotify: true,
      actions: [
        { action: 'confirm', title: 'Check offer', icon: '' },
      ],
    };
    navigator.serviceWorker.ready.then(swreg => {
      swreg.showNotification(newOffer.heading, options);
    });
  } else {
    console.log('no serviceWorker');
  }
}

And this is how I call it:

function addedOfferSubs<T>(setOffers: (offers:any) => void) {
  // @ts-ignore
  const subscription = API.graphql(graphqlOperation(addedOffer)).subscribe({
    next: async (eventData: SubscriptionValue<T>) => {
      const newOffer = (eventData.value.data as any).addedOffer;
      await indexedDb.createObjectStore('offers', 'id'); // Opens db. Will create the table offers only if it doesnt already exist 
      await indexedDb.putValue('offers', newOffer); // Adds new offer
      // Push notification
      notifyNewOffer(newOffer);
      // Set offers
      const offersData = await getOffersFromIdb();
      setOffers(offersData);
    },
  });
  return () => subscription.unsubscribe()
}

Any ideas ? Thanks very much


Solution

  • In order for notifications to appear when the app isn't open, you'll need to use Web Push as well. Web push allows you to send a notification from your server to device. When the push arrives on the device, it wakes up the service worker, and the notification is shown there.

    Instructions for setting up Web Push & Notifications are available at https://developers.google.com/web/fundamentals/push-notifications