aboutsummaryrefslogtreecommitdiff
path: root/src/sw.js
blob: 6cecb3f380004f918b313f2068ac67541fdeccb1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/* eslint-env serviceworker */

import localForage from 'localforage'

function isEnabled () {
  return localForage.getItem('vuex-lz')
    .then(data => data.config.webPushNotifications)
}

function getWindowClients () {
  return clients.matchAll({ includeUncontrolled: true })
    .then((clientList) => clientList.filter(({ type }) => type === 'window'))
}

self.addEventListener('push', (event) => {
  if (event.data) {
    event.waitUntil(isEnabled().then((isEnabled) => {
      return isEnabled && getWindowClients().then((list) => {
        const data = event.data.json()

        if (list.length === 0) return self.registration.showNotification(data.title, data)
      })
    }))
  }
})

self.addEventListener('notificationclick', (event) => {
  event.notification.close()

  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('/')
  }))
})