Events (listen to messages)
Listen for messages posted by the widget iframes. Always validate the origin.
Subscribe
const WIDGET_ORIGIN = 'https://DOMAIN'
window.addEventListener('message', (event) => {
if (event.origin !== WIDGET_ORIGIN) return
const { type, payload } = event.data || {}
switch (type) {
case 'HAS_UNREAD_MESSAGES':
// payload: { count }
break
case 'SET_CHAT_ROOM_ID':
// payload: { chatRoomId }
break
case 'SHOW_ERROR_MESSAGE':
// payload: { message, code? }
break
}
})
Event types
HAS_UNREAD_MESSAGES—{ count: number }SET_CHAT_ROOM_ID—{ chatRoomId: string }SHOW_ERROR_MESSAGE—{ message: string, code?: string }
Example UI updates
const WIDGET_ORIGIN = 'https://DOMAIN'
const badge = document.querySelector('#unread-badge')
window.addEventListener('message', (event) => {
if (event.origin !== WIDGET_ORIGIN) return
const { type, payload } = event.data || {}
if (type === 'HAS_UNREAD_MESSAGES') {
const count = Number(payload?.count || 0)
badge.textContent = String(count)
badge.style.display = count > 0 ? 'inline-flex' : 'none'
}
})