i'm trying do show a notification and do something when it's clicked.
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);
}
I added the eventlistener but it never gets fired.
What am i doing wrong?
The correct place for handling clicks of Service Worker-based notifications is in Service Worker. You need to move your listener - the part with self.addEventListener('notificationclick', ...)
- to your Service Worker code.
Note that you don't have window
access there. To navigate to the URL, you'd need to use clients.openWindow
instead.
So your app-side code will only have the reg.showNotification
call and your handler in the Service Worker will look like this:
self.addEventListener('notificationclick', function (event) {
event.notification.close();
clients.openWindow("https://youtu.be/PAvHeRGZ_lA");
});