Scott
Scott

Reputation: 3761

How to receive notification data from click when PWA is closed?

I have desktop notifications working just fine in my Progressive Web App (PWA). With the PWA open, when I click the notification, I am able to receive the notification's data property. When the PWA is closed, when I click the notification, the PWA is opened BUT my onclick handler is never executed, nor do I see a way to receive data from the notification on launch of the web app.

How can I receive the notification data property when the PWA is not currently running?

With 2 notifications appearing from my PWA, I want to know which of the PWAs was clicked when my PWA is closed. Looking at the Notification API, I don't see a way to check on startup of my web app.

Here is my code:

if ('Notification' in window) {
    const options = {
        icon: 'https://i.imgur.com/l8qOen5.png',
        image: 'https://i.imgur.com/l8qOen5.png',
        requireInteraction: true,
    };

    if (Notification.permission === 'granted') {
        const desktopNotification = new Notification('My Title', {
            ...options,
            body: 'My body text',
            data: 'A string I want to receive when PWA is opened',
            tag: 'A unique identifier',
        });

        desktopNotification.onclick = (e) => {
            // Not received when PWA is closed and then opened on click of notification
            const data = e.currentTarget.data || {};
            console.log('desktopNotification clicked!', e, data);
        };
    }
}

Upvotes: 4

Views: 3711

Answers (1)

pepsilike
pepsilike

Reputation: 226

First of all, you need to have the service-worker.js running, even if your PWA application is closed. If you are not familiar with the Service Worker API, please, have a look at the very good example given here: Introduction to Push Notifications.

To answer your question on a technical level, you need to subscribe to notificationclick events from within the service-worker.js. A couple of other events are also available, for example: notificationclose.

Here is a brief example of what is required to be inside serviceworker.js:

self.addEventListener('notificationclick', function(e) {
  var notification = e.notification;
  var primaryKey = notification.data.primaryKey;
  var action = e.action;

  if (action === 'close') {
    notification.close();
  } else {
    clients.openWindow('http://www.example.com');
    notification.close();
  }
});

Upvotes: 3

Related Questions