improve push notifications code

This commit is contained in:
Egor Kislitsyn 2018-12-09 19:25:43 +07:00
parent 11716a7a53
commit 73b17d70ec
3 changed files with 48 additions and 65 deletions

View file

@ -1,32 +1,29 @@
/* eslint-env serviceworker */
self.addEventListener('push', function (event) {
function getWindowClients () {
return clients.matchAll({ includeUncontrolled: true })
.then((clientList) => clientList.filter(({ type }) => type === 'window'))
}
self.addEventListener('push', (event) => {
if (event.data) {
const data = event.data.json()
event.waitUntil(getWindowClients().then((list) => {
const data = event.data.json()
const promiseChain = clients.matchAll({
includeUncontrolled: true
}).then(function (clientList) {
const list = clientList.filter((item) => item.type === 'window')
if (list.length) return
return self.registration.showNotification(data.title, data)
})
event.waitUntil(promiseChain)
if (list.length === 0) return self.registration.showNotification(data.title, data)
}))
}
})
self.addEventListener('notificationclick', function (event) {
self.addEventListener('notificationclick', (event) => {
event.notification.close()
event.waitUntil(clients.matchAll({
includeUncontrolled: true
}).then(function (clientList) {
const list = clientList.filter((item) => item.type === 'window')
event.waitUntil(getWindowClients().then((list) => {
for (var i = 0; i < list.length; i++) {
var client = list[i]
if (client.url === '/' && 'focus' in client) { return client.focus() }
}
if (clients.openWindow) { return clients.openWindow('/') }
if (clients.openWindow) return clients.openWindow('/')
}))
})