JavaScript Embed Features

Event Listeners

Listen to chat events from the embedded widget to react to user messages, AI responses, and widget state changes.

Overview

Event Listeners let your host application react to events from the chat widget in real time. The embed widget communicates with the parent page using the browser PostMessage API. Track when the widget is ready, when messages are exchanged, and when errors occur — enabling deep integration between your app and the chatbot.

Available Events

The widget emits three events via postMessage to the parent window: docimal:ready (the widget has finished loading and is ready to accept commands — no payload), docimal:message (a message was sent or received — payload includes id, role ("user" or "assistant"), content, createdAt, sources array, isStreaming boolean, and feedback), and docimal:error (an error occurred — payload is the error message string).

Listening to Events

Add a message event listener to the window: window.addEventListener("message", (event) => { if (event.data.type === "docimal:ready") { console.log("Widget ready"); } if (event.data.type === "docimal:message") { const { role, content } = event.data.payload; console.log(role + ": " + content); } if (event.data.type === "docimal:error") { console.error("Chat error:", event.data.payload); } }). For security, always verify the event origin matches your expected Docimal domain.

SDK Callback Functions

When using the mountChatbot JavaScript SDK, you can pass callback functions directly instead of using PostMessage: mountChatbot(container, { apiKey: "dcml_pk_...", onReady: () => console.log("Ready"), onOpen: () => console.log("Opened"), onClose: () => console.log("Closed"), onMessage: (message) => console.log(message.content), onError: (error) => console.error(error) }). These callbacks provide a cleaner API for the same functionality as PostMessage events.

Common Use Cases

Use event listeners to: track conversation analytics in your own system (forward docimal:message events to Google Analytics or your analytics platform), trigger page navigation when the AI suggests a product, show custom notification UI when new messages arrive, log conversation data to your CRM, and handle errors gracefully with custom error UI. The docimal:ready event is useful for showing a loading state until the widget is initialized.