我注册了一个 Service Worker,并尝试在浏览器中测试 Web 通知。 Chrome(和 Firefox)声称 Service Worker 已成功注册。
加载 React 应用程序时,我已授予接收通知的权限。
在我的
sw.js
中,我正在侦听 push
事件,并尝试从 Chrome 应用程序选项卡发送示例推送消息,如上面的屏幕截图所示。
self.addEventListener("push", receivePushNotification);
单击 Chrome 应用程序选项卡中的
Push
时,会触发 push
事件,调用 receivePushNotification
。但是,当我尝试在浏览器中显示通知时,没有任何反应,也没有报告错误。
function receivePushNotification(event) {
// This prints "Test push message from DevTools."
console.log("[Service Worker] Push Received.", event.data.text());
var options = {
body: "This notification was generated from a push!"
};
/*****
I would expect the following line to display a notification, since I've already
granted permission to allow for notifications. Yet, nothing happens and there is
no error in the console.
*****/
event.waitUntil(self.registration.showNotification("Hello world!", options));
}
您似乎在单独定义函数/不将其定义为异步函数方面走得太远了。您也没有将事件传递给函数调用。
如果你这样重写会发生什么?
self.addEventListener("push", function(event) {
console.log("[Service Worker] Push Received.", event.data.text());
var options = {
body: "This notification was generated from a push!"
};
event.waitUntil(self.registration.showNotification("Hello world!", options));
});
这是我使用的代码。它非常通用,而且有效。
self.addEventListener('push', function (e) {
console.log('Push Received...')
const data = e.data.json()
self.registration.showNotification(data.title, {
body: 'Notified by Waelio.com!',
icon: 'https://picmymenu.s3.eu-west-3.amazonaws.com/waelio_logo.png',
})
})