Chat API overview
The widget API allows you to control the chat widget programmatically and register callbacks for chat events.
Looking for the REST API? This article covers the in-browser JavaScript widget API (window.aichatbotApi) for pages where the ChatLab widget is embedded. For the server-to-server REST API used to converse with bots from your backend or manage bots programmatically, see the Bot Talk API and Management API articles.
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.
Use the public widget key from Deploy as YOUR_API_KEY, never a secret ck_ or mk_ key. Keep the provider ID and script host from your own Deploy snippet. Place the callback setup before that script tag:
<script>
let registeredChatbot;
window.aichatbotCallback = {
onSessionActivated() {
var chatbot = window.aichatbotApi.getChatbotApi('YOUR_API_KEY');
if (registeredChatbot === chatbot) return;
registeredChatbot = chatbot;
chatbot.addCallback('onUserMessage', function(message) {
console.log('User said:', message);
});
chatbot.addCallback('onChatbotMessage', function(message) {
console.log('Bot replied:', message);
});
// Send only when your application intends to start a real chat:
// 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 a session becomes available, including restored sessions. Depending on deployment and welcome-screen settings, this is not necessarily the first widget-opening click. It can fire again; register callbacks once per API object to avoid duplicate handlers. 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 aichatbotReady DOM 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) |
setLanguage(code) |
Switch the widget to a language (multi-language bots only, see below) |
getLanguage() |
Return the language the widget is currently using |
getAvailableLanguages() |
Return the list of languages the bot offers |
addCallback(name, fn) |
Register an event callback |
Note: sendMessage and updateClientContext require an active session. Use the onSessionActivated initialization 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 |
Product/link payload from the rendered card | User clicked a product link; inspect the payload for your card type |
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, not proof an operator joined |
onCustomFormSubmit |
{formId, values} |
Custom form was submitted; uploaded file data is not included in this callback |
Form callbacks report a browser-side submission, not confirmed persistence or successful delivery. For backend-confirmed processing, use Webhooks. Callback payloads can contain personal data; do not forward them wholesale to analytics or public logs.
Legacy Event Callbacks
The window.aichatbotCallback object also supports onUserMessage and onChatbotMessage as direct properties. Use addCallback() for modular listeners without replacing the global object:
window.aichatbotCallback = {
onUserMessage(message) { ... },
onChatbotMessage(message) { ... }
};
Note: window.aichatbotCallback.onSessionActivated is 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
// Give the ChatLab iframe from Deploy this unique id.
const chatbotIframe = document.getElementById('chatlab-frame');
const chatbotOrigin = new URL(chatbotIframe.src, window.location.href).origin;
// Run show/hide/language commands after the iframe loads.
// Wait for onSessionActivated before sendMessage or updateClientContext.
// Show chat
chatbotIframe.contentWindow.postMessage({
type: 'aichatbot',
action: 'showChat'
}, chatbotOrigin);
// Hide chat
chatbotIframe.contentWindow.postMessage({
type: 'aichatbot',
action: 'hideChat'
}, chatbotOrigin);
// Send message
chatbotIframe.contentWindow.postMessage({
type: 'aichatbot',
action: 'sendMessage',
payload: 'Hello!'
}, chatbotOrigin);
// Update client context
chatbotIframe.contentWindow.postMessage({
type: 'aichatbot',
action: 'updateClientContext',
payload: { clientId: 'user123', clientName: 'John' }
}, chatbotOrigin);
// Switch language (multi-language bots only)
chatbotIframe.contentWindow.postMessage({
type: 'aichatbot',
action: 'setLanguage',
payload: 'de'
}, chatbotOrigin);
Receiving Callbacks
window.addEventListener('message', (event) => {
if (event.origin !== chatbotOrigin || event.source !== chatbotIframe.contentWindow) return;
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): A token forwarded as context for your custom integration. Your own API must validate its authenticity, expiry, and authorization.
- clientHostContext (optional): Additional context parameters accessible in custom API actions
Browser-provided IDs and context are not proof of identity. Do not put account-wide secrets in page JavaScript, and do not grant access solely because a supplied clientId or email matches a record.
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
Language
These methods work only on multi-language chatbots. On a single-language bot the widget has no language layer to switch, so setLanguage() does nothing and getAvailableLanguages() returns just the bot's own language. Turn multi-language support on in Settings > Languages first - see Multilingual chatbots.
Use setLanguage() when your page exists in several languages and you want the chat to open in the one the visitor is reading, instead of the one their browser happens to be set to:
window.addEventListener('aichatbotReady', function(e) {
var chatbot = window.aichatbotApi.getChatbotApi(e.detail.apiKey);
chatbot.setLanguage(document.documentElement.lang); // e.g. "de"
console.log(chatbot.getLanguage()); // "de"
console.log(chatbot.getAvailableLanguages()); // ["en", "de", "fr", ...]
});
You can also declare the page language before the script loads, which avoids a brief flash of the wrong language:
<script>window.aichatbotLanguage = "de";</script>
Which language wins. The widget resolves the language in this order:
- A language the visitor picked themselves in the widget's own language menu.
- The page language, from
setLanguage()orwindow.aichatbotLanguage. - The visitor's browser language.
- The chatbot's base language.
A visitor's own pick is remembered for later visits, but it stops applying once the page language changes - so your language switcher always wins over a stale choice. Codes are ISO 639-1 (en, de, pl); a regional code such as de-AT falls back to de. A language the bot does not offer is ignored.
Switching the language does not end the conversation or clear the transcript.