【问题标题】:How do you send a web push notification over FCM from server with actions?您如何通过 FCM 从服务器发送带有操作的 Web 推送通知?
【发布时间】:2019-06-10 01:57:28
【问题描述】:

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

当我点击通知时,它什么也不做(甚至不带我去网站)。如何启用这样的功能?

目前我正在传递一个像

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

【问题讨论】:

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


    【解决方案1】:

    在 service worker 中,监听全局 push 事件来手动处理你的通知。 然后调用showNotification() 方法来显示通知。 在选项对象中,您可以指定通知将具有的操作按钮列表。

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

    【讨论】:

      猜你喜欢
      • 2017-05-26
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-07
      • 2018-02-10
      • 2022-09-28
      • 1970-01-01
      相关资源
      最近更新 更多