JavaScript轻应用PWA实践全过程( 四 )

self.registration.showNotification 中data是可以传额外的参数 。
有个细节,官方没有提到的,需要用setTimeout包着showNotification,Chrome推送出的消息才不会出现链接无法点击的问题 。
监听推送消息的点击事件
// 推送消息点击事件self.addEventListener('notificationclick', event => { console.log('notificationclick'); const clickedNotification = event.notification; const urlToOpen = new URL(clickedNotification.data.href, self.location.origin).href; let promiseChain = clients.matchAll({ type: 'window', includeUncontrolled: true }).then(windowClients => { let matchingClient = null; for (let i = 0, max = windowClients.length; i < max; i++) { let windowClient = windowClients[i]; if (windowClient.url.split('?')[0] === urlToOpen.split('?')[0]) { matchingClient = windowClient; break; } } return matchingClient ? matchingClient.focus() : clients.openWindow(urlToOpen); }); event.waitUntil(promiseChain); clickedNotification.close();});监听 notificationclick 点击事件,除了需要打开弹窗,还要判断该弹窗是否曾经打开过,如果是则只需active tab即可 。
参考链接
https://www.boatsky.com/blog/66




推荐阅读