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',
}));
};
I must be late but for future readers
showNotificationThe 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);
}));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With