Search code examples
javascriptgoogle-chromepush-notification

Chrome push notification - how to open URL adress after click?


I am new to Google Chrome Push notifications and I was just reading some questions and answers here, on stackoverflow and I have ended with this easy push notification javascript.

  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',
                });

            });
        }
    });

}

Its just simple notification, but I need open a new window with other webpage after click on notification.

I know it is possible, but I cant find examples using "serviceWorker" syntax.

Please help. Thanks.


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);
                }
            })
        );
    });