首页 > 解决方案 > 不发送推送通知

问题描述

我对推送通知有疑问。我在firebase函数日志中有这个错误:

错误:要发送带有有效负载的消息,订阅必须具有“auth”和“p256dh”键。

 exports.storePostData = functions.https.onRequest(
 (request, response) => {
     cors(request, response, () => {
         admin.database().ref('posts').push({
             id: request.body.id,
             title: request.body.title,
             location: request.body.location,
             image: request.body.image
         }).then(() => {
             webpush.setVapidDetails('mailto: xxxx@gmail.com', 'BLl7xIPAyJNzsMi5vo_aG-4RdXdyZ4Q4ZFpTgnm902qN79MIiSORBk9N-rfFEGiKNPuJu5SJmUX35Wwce9nuH94', 'M8E6hw7jCmu7qNQJ88FV5o02OAiLefEFJK8jyJimk7g')

             return admin.database().ref('subscriptions').once('value');
         }).then(subscriptions => {
             subscriptions.forEach(sub => {
                 var pushConfig = {
                     endpoint: sub.val().endpoint,
                     keys: {
                         auth: sub.val().keys,
                         p256dh: sub.val().p256dh
                     }
                 }
                 webpush.sendNotification(pushConfig, JSON.stringify({
                     title: 'New Post',
                     content: 'New post added',
                     openUrl: '/help'
                 })).catch(err => {
                     console.log(err)
                 })
             })
             response.status(201).json({
                 message: 'Data stored',
                 id: request.body.id
             })
         }).catch(err => {
             response.status(500).json({
                 error: err
             })
         })
     })
 });

这是我用于存储帖子数据的功能,我认为问题出在这里,因为它甚至无法在 serviceWorker 中推送事件(我在那里没有任何日志)。

标签: javascriptfirebaseweb-pushpwa

解决方案


在客户端,您应该能够在 Angular 上检索订阅,就像

    const sw = await navigator.serviceWorker.register('/assets/js/service-worker.js', { scope: '/assets/js/' });

      let subscription = await sw.pushManager.getSubscription();

通过这种方式,您应该可以获取订阅,并且订阅对象包含 p256dh 和 auth 密钥。

您应该能够通过以下方式查看值

      console.log("subscription: ", subscription?.toJSON());

推荐阅读