sw.js 2.1 KB

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