Chat API overview
This feature is available in selected plans only. It allows you to control the chat widget programmatically and register callbacks for chat events.
Getting Started
The chatbot API is not available immediately when your page loads — the script must load and initialize first. You must use window.aichatbotCallback.onSessionActivated as the bootstrap mechanism to safely access the API.
Place this before the ChatLab script tag:
<script>
window.aichatbotCallback = {
onSessionActivated() {
var chatbot = window.aichatbotApi.getChatbotApi('YOUR_API_KEY');
chatbot.addCallback('onUserMessage', function(message) {
console.log('User said:', message);
});
chatbot.addCallback('onChatbotMessage', function(message) {
console.log('Bot replied:', message);
});
chatbot.sendMessage('Hello from the API!');
}
};
</script>
<script>window.aichatbotApiKey="YOUR_API_KEY";</script>
<script src="https://script.chatlab.com/aichatbot.js" defer></script>
onSessionActivated fires when the chat session is created (i.e., the user opens the widget). Inside it, the API object is guaranteed to exist and the session is active, so you can safely call sendMessage(), updateClientContext(), and register event callbacks.
Important: Do not call
window.aichatbotApi.getChatbotApi()directly in your page script without waiting — the API object does not exist until the ChatLab script has loaded and initialized.
Tip: If you only need to control the widget (show/hide/toggle) and don't need an active session, listen for the
aichatbotReadyDOM event instead:window.addEventListener('aichatbotReady', function(e) { var chatbot = window.aichatbotApi.getChatbotApi(e.detail.apiKey); chatbot.showChat(); });
Methods
| Method | Description |
|---|---|
showChat() |
Open the chat widget |
hideChat() |
Close the chat widget |
toggleChat() |
Toggle widget visibility |
sendMessage(text) |
Send a message programmatically |
updateClientContext(data) |
Update user context (see below) |
addCallback(name, fn) |
Register an event callback |
Note:
sendMessageandupdateClientContextrequire an active session. Use theonSessionActivatedinitialization pattern shown in Getting Started.
Callbacks
Register event callbacks inside your onSessionActivated handler (see Getting Started):
chatbot.addCallback('onUserMessage', function(message) {
console.log('User said:', message);
});
chatbot.addCallback('onChatbotMessage', function(message) {
console.log('Bot replied:', message);
});
chatbot.addCallback('onProductClick', function(productIdOrLink) {
console.log('Product clicked:', productIdOrLink);
});
chatbot.addCallback('onLeadCollectionFormSubmit', function(data) {
console.log('Lead captured:', data.email);
});
chatbot.addCallback('onContactFormSubmit', function(data) {
console.log('Support request from:', data.email);
});
chatbot.addCallback('onLiveChatFormSubmit', function(data) {
console.log('Live chat started:', data.name);
});
Available Callbacks
| Callback | Data | Description |
|---|---|---|
onSessionActivated |
- | Chat session is ready |
onUserMessage |
string |
User sent a message |
onChatbotMessage |
string |
Bot replied with a message |
onProductClick |
string (product ID or link) |
User clicked on a product (requires Products View enabled) |
onLeadCollectionFormSubmit |
{email, phone, name} |
Lead collection form was submitted |
onContactFormSubmit |
{email, message} |
Contact/support form was submitted |
onLiveChatFormSubmit |
{name, email} |
Live chat form was submitted |
Legacy Event Callbacks (Deprecated)
The window.aichatbotCallback object also supports onUserMessage and onChatbotMessage as direct properties. This format is deprecated — use addCallback() instead for access to all callback types:
window.aichatbotCallback = {
onUserMessage(message) { ... },
onChatbotMessage(message) { ... }
};
Note:
window.aichatbotCallback.onSessionActivatedis not deprecated — it is the recommended bootstrap mechanism for initializing the Chat API (see Getting Started).
Iframe Deployment
When using iframe deployment, use postMessage to communicate with the chatbot:
Sending Commands
const chatbotIframe = document.querySelector('iframe');
// Show chat
chatbotIframe.contentWindow.postMessage({
type: 'aichatbot',
action: 'showChat'
}, '*');
// Hide chat
chatbotIframe.contentWindow.postMessage({
type: 'aichatbot',
action: 'hideChat'
}, '*');
// Send message
chatbotIframe.contentWindow.postMessage({
type: 'aichatbot',
action: 'sendMessage',
payload: 'Hello!'
}, '*');
// Update client context
chatbotIframe.contentWindow.postMessage({
type: 'aichatbot',
action: 'updateClientContext',
payload: { clientId: 'user123', clientName: 'John' }
}, '*');
Receiving Callbacks
window.addEventListener('message', (event) => {
if (event.data?.type !== 'aichatbot-callback') return;
const { apiKey, callback, data } = event.data;
switch (callback) {
case 'onSessionActivated':
console.log('Session ready');
break;
case 'onUserMessage':
console.log('User said:', data);
break;
case 'onChatbotMessage':
console.log('Bot replied:', data);
break;
case 'onProductClick':
console.log('Product clicked:', data);
break;
case 'onLeadCollectionFormSubmit':
console.log('Lead captured:', data);
break;
case 'onContactFormSubmit':
console.log('Contact form:', data);
break;
case 'onLiveChatFormSubmit':
console.log('Live chat started:', data);
break;
}
});
Update Client Context
The updateClientContext function allows updating client context during an active session:
chatbot.updateClientContext({
clientId: "unique-client-identifier", // Required
clientName: "John", // Optional
clientEmail: "john@doe.com", // Optional
clientPhone: "555-444-333", // Optional
clientSecurityToken: "your-token", // Optional
clientHostContext: { // Optional
param1: "value1",
param2: "value2"
}
});
Parameters:
- clientId (required): Unique identifier for the client
- clientName, clientEmail, clientPhone (optional): Client details displayed in conversations
- clientSecurityToken (optional): Security token for API authorization
- clientHostContext (optional): Additional context parameters accessible in custom API actions
Usage in API calls:
Context attributes can be used in API function calls by configuring the API parameter as type "Context":
clientName,clientEmail,clientPhone,clientSecurityToken- Custom host context parameters prefixed by
client, e.g.,clientparam1,clientparam2