【发布时间】:2020-09-16 07:18:53
【问题描述】:
我注册了一个 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));
}
【问题讨论】:
-
这种情况是仅在生产中发生还是在本地也发生?我确实建议您创建 2 个 vapid 集,一个用于本地测试,另一个用于生产。确保根据您的环境处理调用正确的 vapid 键。我在 github 上有一个你需要的要点。 gist.github.com/waelio/6f2a792e60c0e5ea9441af0cbb4f554c
-
检查操作系统的“请勿打扰”模式是否开启,如本答案所述:stackoverflow.com/a/61651174/3112241
标签: javascript web push-notification service-worker web-notifications