Adding link to payload
Katastrophenmagnet opened this issue · 2 comments
Right now I am using this very example for a small project of mine and have a small issue.
I added a clickListener on the notification, so that the user follows a certain link upon clicking the notification. Looks like this and works fine:
from my serviceWorker.js
self.addEventListener('notificationclick', function(event) {
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(
clients.matchAll({
type: "window"
})
.then(function(clientList) {
console.log(clientList);
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == '/' && 'focus' in client)
return client.focus();
}
if (clients.openWindow) {
console.log(clients.openWindow);
return clients.openWindow(LINK);
}
})
);
}
My problem is that the link is a variable in serviceWorker.js but I'd like it to be sent from the backend, therefore I'd like to attach the data (link) in the file send_push_notification.php at this part:
$res = $webPush->sendNotification( $subscription, "Hello!", true );
and then read it somewhere here in the serviceWorker.js
self.addEventListener('push', function (event) {
eventData = event.data;
if (!(self.Notification && self.Notification.permission === 'granted')) {
return;
}
const sendNotification = body => {
// you could refresh a notification badge here with postMessage API
const title = "Web Push example";
return self.registration.showNotification(title, {
body,
});
};
if (event.data) {
const message = event.data.text();
event.waitUntil(sendNotification(message));
}
});
Could you please explain me how exactly this would be done? I am somewhat confused since I am not fit in php (need it though), tried some stuff, nothing really seemed to do the trick.
Thank you!
Hello!
Just wanted to let you know, that after some time of trying I found out that one possibility would be to just add a json object here instead of "Hello!":
$res = $webPush->sendNotification( $subscription, "Hello!", true );
and then read it via event.data.json() instead of event.data.text() here:
if (event.data) { const message = event.data.text(); event.waitUntil(sendNotification(message)); }
Sorry and thank you!
If you have better ideas I am all ears.
BTW: Is there some good and exact documentation for all this?
Hello,
Cool that you found the solution by yourself. You have several examples here, I highly recommend the Web Push book.