106 lines
2.8 KiB
JavaScript
106 lines
2.8 KiB
JavaScript
// apps/web/public/sw.js
|
|
// D3RO Voice — Web Push Service Worker
|
|
|
|
const DEFAULT_TITLE = 'D3RO Voice'
|
|
const DEFAULT_BODY = '새 알림이 도착했습니다.'
|
|
const DEFAULT_TARGET_URL = '/app/dashboard'
|
|
|
|
function sanitizeTargetUrl(rawUrl) {
|
|
if (typeof rawUrl !== 'string' || !rawUrl.trim()) {
|
|
return DEFAULT_TARGET_URL
|
|
}
|
|
const trimmed = rawUrl.trim()
|
|
if (!trimmed.startsWith('/') || trimmed.startsWith('//') || trimmed.startsWith('/\\')) {
|
|
return DEFAULT_TARGET_URL
|
|
}
|
|
return trimmed.startsWith('/app/') || trimmed === '/app'
|
|
? trimmed
|
|
: `/app${trimmed}`
|
|
}
|
|
|
|
function parsePushPayload(event) {
|
|
if (!event.data) {
|
|
return {
|
|
title: DEFAULT_TITLE,
|
|
body: DEFAULT_BODY,
|
|
tag: 'd3ro-notification',
|
|
url: DEFAULT_TARGET_URL,
|
|
}
|
|
}
|
|
|
|
try {
|
|
const parsed = event.data.json()
|
|
if (typeof parsed === 'object' && parsed !== null) {
|
|
const title = typeof parsed.title === 'string' && parsed.title.trim()
|
|
? parsed.title.trim()
|
|
: DEFAULT_TITLE
|
|
const body = typeof parsed.body === 'string' && parsed.body.trim()
|
|
? parsed.body.trim()
|
|
: DEFAULT_BODY
|
|
const tag = typeof parsed.tag === 'string' && parsed.tag.trim()
|
|
? parsed.tag.trim()
|
|
: 'd3ro-notification'
|
|
const rawUrl = typeof parsed.url === 'string'
|
|
? parsed.url
|
|
: typeof parsed.data?.url === 'string'
|
|
? parsed.data.url
|
|
: DEFAULT_TARGET_URL
|
|
return {
|
|
title,
|
|
body,
|
|
tag,
|
|
url: sanitizeTargetUrl(rawUrl),
|
|
}
|
|
}
|
|
} catch {
|
|
const text = event.data.text()
|
|
return {
|
|
title: DEFAULT_TITLE,
|
|
body: text && text.trim() ? text.trim() : DEFAULT_BODY,
|
|
tag: 'd3ro-notification',
|
|
url: DEFAULT_TARGET_URL,
|
|
}
|
|
}
|
|
|
|
return {
|
|
title: DEFAULT_TITLE,
|
|
body: DEFAULT_BODY,
|
|
tag: 'd3ro-notification',
|
|
url: DEFAULT_TARGET_URL,
|
|
}
|
|
}
|
|
|
|
self.addEventListener('push', (event) => {
|
|
const payload = parsePushPayload(event)
|
|
event.waitUntil(
|
|
self.registration.showNotification(payload.title, {
|
|
body: payload.body,
|
|
tag: payload.tag,
|
|
data: { url: payload.url },
|
|
}),
|
|
)
|
|
})
|
|
|
|
self.addEventListener('notificationclick', (event) => {
|
|
event.notification.close()
|
|
const targetUrl = sanitizeTargetUrl(event.notification?.data?.url)
|
|
|
|
event.waitUntil(
|
|
self.clients
|
|
.matchAll({ type: 'window', includeUncontrolled: true })
|
|
.then((windowClients) => {
|
|
for (const client of windowClients) {
|
|
if ('focus' in client) {
|
|
if ('navigate' in client && typeof client.navigate === 'function') {
|
|
return client.navigate(targetUrl).then(() => client.focus())
|
|
}
|
|
return client.focus()
|
|
}
|
|
}
|
|
if (self.clients.openWindow) {
|
|
return self.clients.openWindow(targetUrl)
|
|
}
|
|
return undefined
|
|
}),
|
|
)
|
|
})
|