PWA服务人员通知请点击

mar*_*eto 4 javascript notifications progressive-web-apps

我正在尝试显示通知,并在单击时做一些事情。

    try {
    navigator.serviceWorker.getRegistration()
        .then(reg => {
            reg.showNotification("Guarda il videoclip!", {
                body: "clicca qua!",
                icon: "images/she_is_fire.png",
                vibrate: [100, 50, 100],
                tag: 'sample',
                actions: [{ action: 'explore', title: 'Guarda', icon: 'images/she_is_fire.png' }],
            });
            self.addEventListener('notificationclick', function(event) {
                event.notification.close();
                window.open("https://youtu.be/PAvHeRGZ_lA");
            }, false);
        })
        .catch(err => alert('Service Worker registration error: ' + err));

} catch (err) {
    alert('Notification API error: ' + err);
}
Run Code Online (Sandbox Code Playgroud)

我添加了事件监听器,但从未触发。

我究竟做错了什么?

NOt*_*Dev 7

处理基于Service Worker的通知的单击的正确位置在Service Worker中。您需要将侦听器(附带的部分self.addEventListener('notificationclick', ...))移至Service Worker代码。

请注意,您在window那里没有访问权限。要导航到该URL,您需要使用clients.openWindow来代替。

因此,您的应用程序端代码将仅具有该reg.showNotification调用,并且您在Service Worker中的处理程序将如下所示:

self.addEventListener('notificationclick', function (event) {
  event.notification.close();
  clients.openWindow("https://youtu.be/PAvHeRGZ_lA");
});
Run Code Online (Sandbox Code Playgroud)