如何通过FCM从服务器发送带有操作的Web推送通知?

时间:2019-01-16 01:39:51

标签: firebase-cloud-messaging service-worker progressive-web-apps firebase-notifications web-push

我正在使用Firebase从服务器成功通过FCM发送Web推送通知。我缺少的一件事是与此同时发送事件。

当我单击通知时,它什么也没做(甚至不带我去该站点)。如何启用类似功能?

当前,我正在传递

之类的JSON对象
{
    "to": "[add your token]",
    "notification": {
        "title": "Working Good",
        "body": "[add your message]"
    },
    "priority": "high"
}

1 个答案:

答案 0 :(得分:1)

在服务工作者中,侦听全局push事件以手动处理您的通知。 然后调用showNotification()方法以显示通知。 在options对象中,您可以指定通知将具有的操作按钮列表。

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"
        }],
    }));

});

收听notificationclick事件以处理对操作按钮或通知本身的单击:

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("/");

    }

});
相关问题