通知点击事件服务工作者 [英] notificationclick event service worker

查看:84
本文介绍了通知点击事件服务工作者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


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


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...

这是我当前的代码:

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

推荐答案

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

这篇关于通知点击事件服务工作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆