Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initiate a PWA (progressive webapp) open from a click on a push notification?

Following this example, I see how PWA can open urls but how can I use push notification to launch the app itself? Not in the browser but the full screen version PWA.

like image 595
jasan Avatar asked Aug 02 '16 06:08

jasan


2 Answers

Found a solution that worked for me right here.

Just add this to your service worker:

self.addEventListener('notificationclick', function(event) {
  console.log('On notification click: ', event.notification.tag);
  // Android doesn't close the notification when you click on it
  // See: http://crbug.com/463146
  event.notification.close();

  // This looks to see if the current is already open and
  // focuses if it is
  event.waitUntil(
    clients.matchAll({
      type: "window"
    })
    .then(function(clientList) {
      for (var i = 0; i < clientList.length; i++) {
        var client = clientList[i];
        if (client.url == '/' && 'focus' in client)
          return client.focus();
      }
      if (clients.openWindow) {
        return clients.openWindow('/');
      }
    })
  );
});
like image 112
YogliB Avatar answered Sep 28 '22 01:09

YogliB


Taken from Jake Archibald's emojoy demo:

self.addEventListener('notificationclick', event => {
    const rootUrl = new URL('/', location).href;
    event.notification.close();
    // Enumerate windows, and call window.focus(), or open a new one.
    event.waitUntil(
      clients.matchAll().then(matchedClients => {
        for (let client of matchedClients) {
          if (client.url === rootUrl) {
            return client.focus();
          }
        }
        return clients.openWindow("/");
      })
    );
});
like image 32
Kevin Farrugia Avatar answered Sep 28 '22 02:09

Kevin Farrugia