Reputation: 647
I am successfully sending web push notifications over FCM from the server using Firebase. One thing I am missing though is sending events along with this.
When I click on the notification it does nothing (not even take me to the site). How do I enable something like that?
Currently I am passing a JSON object like
{
"to": "[add your token]",
"notification": {
"title": "Working Good",
"body": "[add your message]"
},
"priority": "high"
}
Upvotes: 1
Views: 1162
Reputation: 504
In service worker, listen to global push
event to handle your notification manually.
Then call showNotification()
method to display the notification.
In options object you can specify a list of action buttons your notification would have.
self.addEventListener("push", event => {
const {title, body} = JSON.parse(event.data.text());
event.waitUntil(self.registration.showNotification(title, {
body,
actions: [{
action: "delete",
title: "Delete"
}, {
action: "markAsRead",
title: "Mark as read"
}],
}));
});
Listen to notificationclick
event to handle clicks on your action buttons or notification itself:
self.addEventListener("notificationclick", event => {
// Hide the notification
event.notification.close();
switch (event.notification.data.action) {
// If an action button has been clicked
case "delete":
case "markAsRead":
// Send some request to your server
break;
// User haven't clicked any action buttons, only the notification itself
default:
// Opening a tab
clients.openWindow("/");
}
});
Upvotes: 3