notificationclick event service worker

孤街醉人 提交于 2019-12-11 03:42:23

问题



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('/');
            })
       );
   };
});

回答1:


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


来源:https://stackoverflow.com/questions/52225110/notificationclick-event-service-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!