akkoma-fe/src/sw.js

39 lines
1 KiB
JavaScript
Raw Normal View History

/* eslint-env serviceworker */
2018-12-12 17:03:50 +00:00
import localForage from 'localforage'
function isEnabled () {
return localForage.getItem('vuex-lz')
.then(data => data.config.webPushNotifications)
}
2018-12-09 12:25:43 +00:00
function getWindowClients () {
return clients.matchAll({ includeUncontrolled: true })
.then((clientList) => clientList.filter(({ type }) => type === 'window'))
}
self.addEventListener('push', (event) => {
if (event.data) {
2018-12-12 17:03:50 +00:00
event.waitUntil(isEnabled().then((isEnabled) => {
return isEnabled && getWindowClients().then((list) => {
const data = event.data.json()
2018-12-12 17:03:50 +00:00
if (list.length === 0) return self.registration.showNotification(data.title, data)
})
2018-12-09 12:25:43 +00:00
}))
}
})
2018-12-09 12:25:43 +00:00
self.addEventListener('notificationclick', (event) => {
event.notification.close()
2018-12-09 12:25:43 +00:00
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() }
}
2018-12-09 12:25:43 +00:00
if (clients.openWindow) return clients.openWindow('/')
}))
})