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

34,439

Solution 1

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

Solution 2

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!

Solution 3

(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.

Share:
34,439

Related videos on Youtube

shitwithcode
Author by

shitwithcode

Updated on April 06, 2022

Comments

  • shitwithcode
    shitwithcode about 2 years

    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.

  • patrick
    patrick over 6 years
    I needed this modification, clients.matchAll({ includeUncontrolled: true, type: 'window' }), to get it to work.
  • Skeets
    Skeets over 4 years
    The other answers did nothing.... clicking the notification didn't open anything. This answer works and is much simpler.
  • wirher
    wirher over 4 years
    click_action is not a part of official browser Notification API. Above answer is for Firebase push notifications only.
  • stackers
    stackers over 4 years
    what is this mysterious undefined "clients" variable supposed to be
  • C14L
    C14L over 4 years
  • S.Aminnejad
    S.Aminnejad over 3 years
    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 me
  • Duc Trung Mai
    Duc Trung Mai over 3 years
    Works perfectly, @S.Aminnejad you can place this in firebase-messaging-sw.js
  • IStranger
    IStranger almost 3 years
    There is no such option in official Notification API: developer.mozilla.org/en-US/docs/Web/API/Notification
  • user3502626
    user3502626 about 2 years
    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.