Examples & Recipes

Open on your page CTA

const btn = document.querySelector('#open-help')
btn.addEventListener('click', () => {
  window.postMessage({ type: 'WIDGET_OPEN' }, window.location.origin)
})
		

Mirror unread badge

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'
  }
})
		

Custom error toast

const WIDGET_ORIGIN = 'https://DOMAIN'
const showToast = (msg) => {
  // implement with your UI lib
  alert(msg)
}
window.addEventListener('message', (event) => {
  if (event.origin !== WIDGET_ORIGIN) return
  const { type, payload } = event.data || {}
  if (type === 'SHOW_ERROR_MESSAGE') {
    showToast(payload?.message || 'An error occurred')
  }
})