我正在与 service worker 合作,在我的用户之间显示通知。在我的代码中,我包含了 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('/');
})
);
};
});
最佳答案
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);
}
}());
});
关于javascript - notificationclick 事件服务 worker ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52225110/