// public/sw.js
var WRITE_KEY = ''
var ZIXFLOW_API = 'https://cdp.zixflow.com/v1/track'
self.__ZIXFLOW_USER_ID__ = null
self.addEventListener('message', function (event) {
var msg = event.data || {}
if (msg.type === 'SDK_CONFIG') {
if (msg.apiKey) WRITE_KEY = msg.apiKey
if (msg.apiBase) {
ZIXFLOW_API = String(msg.apiBase).replace(/\/$/, '') + '/track'
}
}
if (msg.type === 'SET_USER_ID') {
self.__ZIXFLOW_USER_ID__ = msg.userId || null
}
if (msg.type === 'SET_WRITE_KEY' && msg.writeKey) {
WRITE_KEY = msg.writeKey
}
})
function parseActionButtonsRaw(raw) {
if (!raw) return []
try {
return typeof raw === 'string' ? JSON.parse(raw) : raw
} catch (e) {
return []
}
}
function parseActionButtons(raw) {
return parseActionButtonsRaw(raw)
.slice(0, 2)
.map(function (btn, i) {
return {
action: 'ACTION_' + i,
title: (btn && btn.name) || 'Action ' + (i + 1),
}
})
}
function trackEvent(eventName, properties) {
if (!WRITE_KEY) return Promise.resolve()
return fetch(ZIXFLOW_API, {
method: 'POST',
keepalive: true,
headers: {
'Content-Type': 'application/json',
Authorization: 'Basic ' + btoa(WRITE_KEY + ':'),
},
body: JSON.stringify({
event: eventName,
userId: self.__ZIXFLOW_USER_ID__,
properties: properties,
}),
}).catch(function () {})
}
self.addEventListener('push', function (event) {
if (!event.data) return
var data = event.data.json()
var deliveryId = data['Zixflow-Delivery-ID'] || ''
var token = data['Zixflow-Delivery-Token'] || ''
var buttons = parseActionButtons(data.action_buttons)
var tasks = [
self.registration.showNotification(data.title || 'Notification', {
body: data.body || '',
icon: data.image_url || data.icon || '/icon.png',
data: data,
actions: buttons,
}),
]
if (deliveryId && token) {
tasks.push(
trackEvent('Push Notification Delivered', {
'Zixflow-Delivery-ID': deliveryId,
'Zixflow-Delivery-Token': token,
})
)
}
event.waitUntil(Promise.all(tasks))
})
// notificationclick: track Opened (+ Action Clicked), focus client or openWindow
// — see Push Notification Tracking / example sw.js