marco burrometo
marco burrometo

Reputation: 1135

PWA Service worker notification click

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?

Upvotes: 11

Views: 15543

Answers (4)

user1274820
user1274820

Reputation: 8154

If you're trying to test this locally using a visual studio generated browser window, try opening it in a different browser or deploying it and it will work.

There's some weird glitch with VS and localhost that doesn't have this event fire.

I spent 2 hours debugging this. Hopefully this saves you all some time.

Upvotes: 1

Luis Febro
Luis Febro

Reputation: 1860

Just for complementary explanation, here is why is used self inside a service worker file according to Google Web Fundamentals:

The weirdest bit of this code to most developers who are new to service workers is the self variable. self is commonly used in Web Workers, which a service worker is. self refers to the global scope, kind of like window in a web page. But for web workers and service workers, self refers to the the worker itself.

reference

I am posting this explanation because helped me out understanding all these events including click.

Upvotes: 0

A W
A W

Reputation: 1139

Always remember, after adding code (refer answer ) in service-worker.js , restart your browser to reflect the changes. I was making change and not restarting browser window , got me frustrated !

Upvotes: 4

NOtherDev
NOtherDev

Reputation: 9682

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");
});

Upvotes: 22

Related Questions