Chatbot Event Listeners
Overview
Chatbase enables developers to track and respond to key events during a chatbot’s lifecycle. By using window.chatbase.addEventListener
and window.chatbase.removeEventListener
, you can listen for and handle specific events to create interactive and dynamic user experiences.
This guide explains how to initialize Chatbase, register event listeners, and handle event payloads.
How to Enable Event Listeners
To ensure that the event listeners are available as soon as possible, you need to embed the Chatbase script correctly.
Follow these steps to get the embed code:
- Visit the Chatbase Dashboard.
- Navigate to Connect > Embed > Embed code with identity.
- Copy the embed code and add it to your application.
Here’s an example of the embed code you’ll find on the dashboard:
This script ensures the Chatbase SDK is loaded properly, and the addEventListener
and removeEventListener
methods are available.
Available Event Types
The eventName
parameter must be one of the following enum values:
Event Name | Description | Payload |
---|---|---|
tool-call | Triggered when a tool is called. | { name, type, args, toolCallId } |
tool-result | Triggered when a tool returns a result. | { name, type, result, toolCallId } |
user-message | Triggered when a user sends a message. | { content } |
assistant-message | Triggered when the assistant sends a message. | { content } |
Adding an Event Listener
To listen for a specific event, use the following syntax:
Parameters
eventName
(enum) — Must be one of the event names listed in Available Event Types.callback
(function) — Function to be called when the event is fired. The event payload is passed as an argument.
Example
Listen for a user message:
Removing an Event Listener
To remove a listener for a specific event, use the following syntax:
Parameters
eventName
(enum) — Must be one of the event names listed in Available Event Types.callback
(function) — The exact callback function used when adding the event listener.
Example
Remove a user message listener:
Event Payloads
Each event type has a specific payload. Below are the details for each event type:
-
tool-call
-
tool-result
-
user-message
-
assistant-message
Troubleshooting
If you encounter issues, consider the following tips:
- Check the event name. Ensure you’re using a valid event name listed in Available Event Types.
- Match the callback function. Ensure the callback reference used in
removeEventListener
matches the one used inaddEventListener
. - Check SDK initialization. Ensure the Chatbase script has loaded before registering event listeners.