sw.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* eslint-env serviceworker */
  2. import localForage from 'localforage'
  3. import { parseNotification } from './services/entity_normalizer/entity_normalizer.service.js'
  4. import { prepareNotificationObject } from './services/notification_utils/notification_utils.js'
  5. import { createI18n } from 'vue-i18n'
  6. import messages from './i18n/service_worker_messages.js'
  7. const i18n = createI18n({
  8. // By default, use the browser locale, we will update it if neccessary
  9. locale: 'en',
  10. fallbackLocale: 'en',
  11. messages
  12. })
  13. function isEnabled () {
  14. return localForage.getItem('vuex-lz')
  15. .then(data => data.config.webPushNotifications)
  16. }
  17. function getWindowClients () {
  18. return clients.matchAll({ includeUncontrolled: true })
  19. .then((clientList) => clientList.filter(({ type }) => type === 'window'))
  20. }
  21. const setLocale = async () => {
  22. const state = await localForage.getItem('vuex-lz')
  23. const locale = state.config.interfaceLanguage || 'en'
  24. i18n.locale = locale
  25. }
  26. const maybeShowNotification = async (event) => {
  27. const enabled = await isEnabled()
  28. const activeClients = await getWindowClients()
  29. await setLocale()
  30. if (enabled && (activeClients.length === 0)) {
  31. const data = event.data.json()
  32. const url = `${self.registration.scope}api/v1/notifications/${data.notification_id}`
  33. const notification = await fetch(url, { headers: { Authorization: 'Bearer ' + data.access_token } })
  34. const notificationJson = await notification.json()
  35. const parsedNotification = parseNotification(notificationJson)
  36. const res = prepareNotificationObject(parsedNotification, i18n)
  37. self.registration.showNotification(res.title, res)
  38. }
  39. }
  40. self.addEventListener('push', async (event) => {
  41. if (event.data) {
  42. event.waitUntil(maybeShowNotification(event))
  43. }
  44. })
  45. self.addEventListener('notificationclick', (event) => {
  46. event.notification.close()
  47. event.waitUntil(getWindowClients().then((list) => {
  48. for (let i = 0; i < list.length; i++) {
  49. const client = list[i]
  50. if (client.url === '/' && 'focus' in client) { return client.focus() }
  51. }
  52. if (clients.openWindow) return clients.openWindow('/')
  53. }))
  54. })