notificationclick事件服务工作者

问题描述 投票:1回答:1

我正在与服务工作者一起在我的用户之间显示通知。在我的代码中,我包括notificationclick事件。有了这个事件,我正在尝试管理两个案例。第一种情况,如果在我的浏览器中我的网站页面正在打开,请不要打开它,而是专注于它。第二种情况,如果我的浏览器没有显示我的网站,请打开它并专注于它。但我还没有成功......

这是我目前的代码:

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('/');
            })
       );
   };
});
javascript push-notification service-worker workbox
1个回答
2
投票
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);
        }
    }());
});
© www.soinside.com 2019 - 2024. All rights reserved.