aboutsummaryrefslogtreecommitdiff
path: root/src/sw.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/sw.js')
-rw-r--r--src/sw.js44
1 files changed, 36 insertions, 8 deletions
diff --git a/src/sw.js b/src/sw.js
index 70fed44b..b95d56a4 100644
--- a/src/sw.js
+++ b/src/sw.js
@@ -13,9 +13,9 @@ const i18n = createI18n({
messages
})
-function isEnabled () {
- return localForage.getItem('vuex-lz')
- .then(data => data.config.webPushNotifications)
+const state = {
+ lastFocused: null,
+ notificationIds: new Set()
}
function getWindowClients () {
@@ -29,11 +29,11 @@ const setLocale = async () => {
i18n.locale = locale
}
-const maybeShowNotification = async (event) => {
- const enabled = await isEnabled()
+const showPushNotification = async (event) => {
const activeClients = await getWindowClients()
await setLocale()
- if (enabled && (activeClients.length === 0)) {
+ // Only show push notifications if all tabs/windows are closed
+ if (activeClients.length === 0) {
const data = event.data.json()
const url = `${self.registration.scope}api/v1/notifications/${data.notification_id}`
@@ -48,8 +48,29 @@ const maybeShowNotification = async (event) => {
}
self.addEventListener('push', async (event) => {
+ console.log(event)
if (event.data) {
- event.waitUntil(maybeShowNotification(event))
+ event.waitUntil(showPushNotification(event))
+ }
+})
+
+self.addEventListener('message', async (event) => {
+ const { type, content } = event.data
+
+ if (type === 'desktopNotification') {
+ const { title, ...rest } = content
+ const { tag } = rest
+ if (state.notificationIds.has(tag)) return
+ state.notificationIds.add(tag)
+ setTimeout(() => state.notificationIds.delete(tag), 10000)
+ self.registration.showNotification(title, rest)
+ }
+
+ if (type === 'updateFocus') {
+ state.lastFocused = event.source.id
+
+ const notifications = await self.registration.getNotifications()
+ notifications.forEach(n => n.close())
}
})
@@ -59,7 +80,14 @@ self.addEventListener('notificationclick', (event) => {
event.waitUntil(getWindowClients().then((list) => {
for (let i = 0; i < list.length; i++) {
const client = list[i]
- if (client.url === '/' && 'focus' in client) { return client.focus() }
+ client.postMessage({ type: 'notificationClicked', id: event.notification.tag })
+ }
+
+ for (let i = 0; i < list.length; i++) {
+ const client = list[i]
+ if (state.lastFocused === null || client.id === state.lastFocused) {
+ if ('focus' in client) return client.focus()
+ }
}
if (clients.openWindow) return clients.openWindow('/')