javascriptpush-notificationservice-workerworkbox

notificationclick event service worker



I'm working with service worker to display notification between my users. In my code I include notificationclick event. With this event I'm trying to manage two cases. First case, if in my browser the page of my site is opening, don't open it but focus on it. Second case, if my browser don't show my site, open it and focus on it. But I haven't been succed...

Here is my current code:

self.addEventListener('notificationclick', function (e) {
    console.log('notification was clicked')
    var notification = e.notification;
    var action = e.action;

    if (action === 'close') {
        notification.close();
    } else {
        // This looks to see if the current is already open and
        // focuses if it is
        e.waitUntil(
            self.clients.matchAll().then(function(clientList) {
                console.log(clientList)
                if (clientList.length > 0) {
                    console.log(clientList[0])
                    return clientList[0].focus();
                }
                return self.clients.openWindow('/');
            })
       );
   };
});

Solution

  • self.addEventListener("notificationclick", (event) => {
        event.waitUntil(async function () {
            const allClients = await clients.matchAll({
                includeUncontrolled: true
            });
            let chatClient;
            let appUrl = 'xyz';
            for (const client of allClients) {
            //here appUrl is the application url, we are checking it application tab is open
                if(client['url'].indexOf(appUrl) >= 0) 
                {
                    client.focus();
                    chatClient = client;
                    break;
                }
            }
            if (!chatClient) {
                chatClient = await clients.openWindow(appUrl);
            }
        }());
    });