36

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.

4 Answers 4

73

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);
            }
        })
    );
});
6
  • 4
    I needed this modification, clients.matchAll({ includeUncontrolled: true, type: 'window' }), to get it to work.
    – patrick
    Feb 5, 2018 at 21:06
  • 2
    what is this mysterious undefined "clients" variable supposed to be
    – stackers
    Dec 18, 2019 at 22:58
  • 2
    @stackers developer.mozilla.org/en-US/docs/Web/API/Clients
    – C14L
    Dec 27, 2019 at 16:35
  • 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 Nov 26, 2020 at 7:24
  • 2
    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. Apr 18, 2022 at 7:31
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!

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.

3
  • 1
    The other answers did nothing.... clicking the notification didn't open anything. This answer works and is much simpler.
    – Skeets
    Aug 10, 2019 at 10:34
  • 6
    click_action is not a part of official browser Notification API. Above answer is for Firebase push notifications only.
    – wirher
    Sep 10, 2019 at 18:18
  • There is no such option in official Notification API: developer.mozilla.org/en-US/docs/Web/API/Notification
    – IStranger
    May 28, 2021 at 12:41
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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.