我正在与服务人员一起在我的用户之间显示通知。在我的代码中,我包含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('/');
})
);
};
});
答案 0 :(得分: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);
}
}());
});