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?
As mentioned before, to be able to receive push messages, you have to have a service worker, the basics of which are already explained in the Making PWAs work offline with Service workers article. Inside the service worker, a push service subscription mechanism is created. registration. pushManager.getSubscription().then( /* ...
The Application or PWA: It runs in the browser. Browsers using the Push API contain a push service that is responsible for routing push notifications from the server to the user. The Service Worker: This acts as a proxy server between the application, the browser, and the network
Even when present your service worker won't be available on first load or while it's waiting to activate. Therefore, treat it as optional and do not require it for core functionality. Before a service worker takes control of your page, it must be registered for your PWA.
When active and running, only one instance is typically available no matter how many clients are in memory (such as PWA windows or browser tabs). You should set the scope of your service worker as close to the root of your app as possible. This is the most common setup as it lets the service worker intercept all the requests related to your PWA.
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");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With