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

5

37

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.

Scary answered 9/9, 2016 at 19:30 Comment(0)
P
75

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);
            }
        })
    );
});
Portative answered 12/9, 2016 at 19:20 Comment(7)
I needed this modification, clients.matchAll({ includeUncontrolled: true, type: 'window' }), to get it to work.Weal
what is this mysterious undefined "clients" variable supposed to beDeath
@Death developer.mozilla.org/en-US/docs/Web/API/ClientsPortative
where should I place this eventListener? In my fcm service worker or somewhere else? because I tried it in fcm sw and it didn't work for meWinifield
Works perfectly, @Winifield you can place this in firebase-messaging-sw.jsJemappes
It wasn't working for me. Until I changed matchAll({type: 'window'}) to matchAll({includeUncontrolled: true}). Also I search the host instead of the exact url.Alli
It wasn't working for me alsoBillboard
P
28

If you want to open website with dynamic URL received from FCM push notification or any other web push notification then

BELOW IS AN EXAMPLE OF SERVICE WORKER USED FOR FCM PUSH NOTIFICATION

messaging.setBackgroundMessageHandler(function(payload) {

    console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  var notificationTitle = payload.data.title; //or payload.notification or whatever your payload is
  var notificationOptions = {
    body: payload.data.body,
    icon: payload.data.icon,
    data: { url:payload.data.click_action }, //the url which we gonna use later
    actions: [{action: "open_url", title: "Read Now"}]
  };

  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});

and handle click event with below code

self.addEventListener('notificationclick', function(event) {

  switch(event.action){
    case 'open_url':
    clients.openWindow(event.notification.data.url); //which we got from above
    break;
    case 'any_other_action':
    clients.openWindow("https://www.example.com");
    break;
  }
}
, false);

Hope it helps!

Permutation answered 14/6, 2018 at 8:33 Comment(0)
P
10

(This code refers to firebase messaging) I was also searching for a soluting and the answer was very easy, but there was no doc saying it clearly. You need to put "click_action" = "your url" inside the notification json. Here is an example:

notification: {
          title: "Come",
          icon: '../../../../assets/logo.png',
          vibrate: [300,100,400,100,400,100,400],
          body: "some text",
          click_action : "your link"
         }

Hope it helps.

Paleontology answered 30/7, 2019 at 22:33 Comment(3)
The other answers did nothing.... clicking the notification didn't open anything. This answer works and is much simpler.Winded
click_action is not a part of official browser Notification API. Above answer is for Firebase push notifications only.Arlo
There is no such option in official Notification API: developer.mozilla.org/en-US/docs/Web/API/NotificationZamia
E
0
{

 "notification": {

   "title": "Hey there",

   "body": "Subscribe to might ghost hack youtube channel",

   "click_action" : "http://localhost:4200"

 },

 "to":"YOUR_TOKEN"

}

This worked for me

"@angular/fire": "^6.1.5",

"firebase": "^7.0 || ^8.0"
Eleonoreeleoptene answered 29/6, 2021 at 12:13 Comment(0)
S
0

The answer is simple. Just add the following:

self.addEventListener('push', function(event) {
    console.log('Received a push message', event.data.json());

    // convert string to JSON
    const data = event.data.json();
    const title = data.title;
    
    const options = {
        body: data.body,
        icon: data.icon,
        data : {
            url : data.url
        },
    };
    event.waitUntil(self.registration.showNotification(title, options));
});

self.addEventListener('notificationclick', function(event) {
    clients.openWindow(event.notification.data.url);
}, false);
System answered 17/7, 2024 at 12:5 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.