Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a link on a javascript notification

I've successfully added JavaScript notifications on my app with the code below, but now I would like to implement a redirection link when clicking on the notification. I've looked at different topics here and tried several things with addEventListener, but none of them has worked yet (I'm a newbie in javascript). Does anyone have a solution?

if(document.querySelector('.notification') != null) {
      Notification.requestPermission()
        .then(permisssion => {
            if (permisssion === 'granted') {
                navigator.serviceWorker.ready;
            }
        }).then(() => navigator.serviceWorker.register('service-worker.js'))
        .then(registration => registration.showNotification('👋 magasin Alltricks de Bron', {
            body: 'Un client a besoin de vous, si vous êtes disponible, allez sur l interface vendeur pour vous y positionner',
        }));
  };
like image 633
Julien788 Avatar asked Dec 06 '25 03:12

Julien788


1 Answers

I must be late but for future readers

Adding link to showNotification

The link is added to the data option for the showNotification options see more about showNotification options MDN

if(document.querySelector('.notification') != null) {
      Notification.requestPermission()
        .then(permisssion => {
            if (permisssion === 'granted') {
                navigator.serviceWorker.ready;
            }
        }).then(() => navigator.serviceWorker.register('service-worker.js'))
        .then(registration => registration.showNotification('👋 magasin Alltricks de Bron', {
            body: 'Un client a besoin de vous, si vous êtes disponible, allez sur l interface vendeur pour vous y positionner', data: { link_url: "https://yoursite.com"}
        }));
  };

listen for click on the notification

self.addEventListener("notificationclick", (event) => {
    console.log("Background new notification:");
    event.notification.close();

    event.waitUntil(clients.matchAll({ type: "window" }).then((clientList) => {
        console.log("what is client list", clientList);
        for (const client of clientList) {
            if (client.url === "/" && "focus" in client) return client.focus();
        }
        if (clients.openWindow && Boolean(event.notification.data.link_url)) return clients.openWindow(event.notification.data.link_url);
    }).catch(err => {
        console.log("There was an error waitUntil:", err);
    }));
});
like image 65
Etemire Ewoma Avatar answered Dec 08 '25 16:12

Etemire Ewoma