Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 824
shitwithcode Avatar asked Sep 09 '16 19:09

shitwithcode


People also ask

Can you put a link in a push notification?

How to Add the In-App Link in a Push Notification. After all pending changes are made live, you can begin to add the In-App Link to a push notification. When composing a new push notification in the Mobile App Studio, drag and drop the In-App link draggable into your message.

How do I turn on notifications for a website in Chrome?

Go to Settings > Privacy and Security > Site Settings, then scroll down to Notifications in the pop-up window that appears. From there, you can toggle the Sites Can Ask to Send Notifications switch that turns website notification prompts on or off.

Do push notifications work when browser is closed?

On a desktop device, you can not receive push notifications if your browser is not running. A web push notification can only be delivered if the subscriber is online and the browser is running. Notifications will be delivered via the browser, from websites where you allowed notifications.


3 Answers

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);
            }
        })
    );
});
like image 133
C14L Avatar answered Oct 21 '22 21:10

C14L


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!

like image 26
Rafique Mohammed Avatar answered Oct 21 '22 23:10

Rafique Mohammed


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

like image 6
flyingpig Avatar answered Oct 21 '22 22:10

flyingpig