PHP webpush 库Minishlink\WebPush没有 event.data

问题描述

我已经配置了 webpush 并且一切顺利...我已经注册了 service-worker.js,可以请求权限,将订阅保存到我的数据库,并使用已安装的库从服务器发送推送通知

当我发送推送通知

    [
        'subscription' => Subscription::create($subs_arr),'payload' => '{"title":"test title","msg":"Hello World!","icon":"https://www.newhomesforsale.co.uk/media/chevron.png","url":"https://www.newhomesforsale.co.uk/"}'
    ]
];

我收到一条成功消息:

[v] Message sent successfully for subscription https://fcm.googleapis.com/fcm/send/e2JHJ2YcIfM:APA91bHwU7CruFTDkpAH-zbnJRNhvJEK-mCze2hFNa48mdK8pk-oWuXJUn57Ai9Nw0d-skviCfJ40g1yX7qWKucGHPF3jeNyhkJfZ-8kpxYJNQowrAR561b0dQZJAseL_eBsJRMrxnDP.

浏览器中会出现一条推送消息 - 太好了。

我遇到的问题是 service-worker 文件似乎没有看到有效负载信息,因为该消息甚至显示得非常简单

Oh No - no data {"isTrusted": true}

服务工作者文件

self.addEventListener('push',function(event) {
    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));
    } else {
        do_serverlog('Push event but no data');
        sendNotification("Oh No - no data" + JSON.stringify(event));
    }
});

如果能找到最后一块拼图来弄清楚如何正确发送/读取有效载荷,那就太好了。

解决方法

我发现我在将密钥传递给订阅 ($subs_arr) 时犯了一个错误。

似乎如果您提供了端点,但没有提供密钥,推送通知仍然有效,但数据会被删除。这使我偏离了方向,因为我认为如果钥匙丢失,它根本无法工作。

我想这可能会在某个时候对某人有所帮助。