javascriptgoogle-chromepush-notification

Chrome push notification - How to open an URL address after clicking?


I am new to Google Chrome Push notifications and was just reading some questions and answers here on Stack Overflow and have ended up with this code after doing so:

navigator.serviceWorker.register("sw.js");

function notify() {
   Notification.requestPermission(function (result) {
      if (result === "granted") {
         navigator.serviceWorker.ready.then(function (registration) {
            registration.showNotification("test notification", {
               body: "Hey I am test!",
               icon: "image.png",
            });
         });
      }
   });
}

It's just simple notification I am creating, but now I need open a new window with another webpage after I click on it.

I know it's possible, but I can't find any examples that use a ServiceWorker context.


Solution

  • I am guessing you are in a Service Worker context, because that's where Push Notifications are received. So you have the self object to add a event listener to, that will react to a click on the notification.

    (Place this code in your sw.js file, which is your Service Worker script.)

    self.addEventListener('notificationclick', function(event) {
        let url = 'https://example.com/some-path/';
        event.notification.close(); // Android needs explicit close.
        event.waitUntil(
            clients.matchAll({type: 'window'}).then( windowClients => {
                // Check if there is already a window/tab open with the target URL
                for (var i = 0; i < windowClients.length; i++) {
                    var client = windowClients[i];
                    // If so, just focus it.
                    if (client.url === url && 'focus' in client) {
                        return client.focus();
                    }
                }
                // If not, then open the target URL in a new window/tab.
                if (clients.openWindow) {
                    return clients.openWindow(url);
                }
            })
        );
    });