GitHub Repository | Documentation
The SDK is auto-initialized with the Chatbot ID from the script's data attribute.
Loading...
Programmatically control the chatbot widget's open/closed state and theme.
/**
* Chat Data SDK Implementation Guide
* --------------------------------
* A comprehensive demonstration of all available methods and event listeners.
*/
/* ===========================================
1. INITIALIZATION OPTIONS
=========================================== */
// Method 1: Auto-initialization with data attribute
<script
src="https://www.chat-data.com/static/chatbotsdk.min.js"
data-chatbot-id="YOUR_CHATBOT_ID"></script>
// Method 2: Manual initialization
<script src="https://www.chat-data.com/static/chatbotsdk.min.js"></script>
<script>
window.chatbot.initialize({
chatbot_id: "YOUR_CHATBOT_ID"
});
</script>
// For custom domains
<script
src="https://your-domain.com/static/chatbotsdk.min.js"
data-chatbot-id="YOUR_CHATBOT_ID"></script>
/* ===========================================
2. USER INFORMATION MANAGEMENT
=========================================== */
// Basic user info sending
window.chatbot.sendUserInfo({
userId: "user_12345", // Optional unique user identifier
userHash: "59b403cc509e4f27ed10a6cb440cb2fb74a9fd71b2564ab19cb06527f2a7aa7a", // Optional security hash
name: "John Doe", // Optional
email: "[email protected]", // Optional
phone: "555-123-4567", // Optional
info: "Premium user since 2023-01-01" // Optional additional info
}).then(response => {
console.log("User info sent:", response);
}).catch(error => {
console.error("Error sending user info:", error);
});
// Different info value examples
window.chatbot.sendUserInfo({
userId: "cust_5678",
userHash: "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6a7b8c9d0e1f2",
name: "Jane Smith",
info: "Student account" // Simple text string
});
window.chatbot.sendUserInfo({
userId: "emp_9012",
userHash: "f1e2d3c4b5a6978685746352413f2e1d0c9b8a7968574635241f3e2d1c0b9a87",
email: "[email protected]",
info: JSON.stringify({ // Stringified JSON for structured data
plan: "premium",
signupDate: "2023-01-01"
})
});
// Clearing user information
window.chatbot.clearUserInfo()
.then(response => {
console.log("User info cleared:", response);
})
.catch(error => {
console.error("Error clearing user info:", error);
});
/* ===========================================
3. WIDGET CONTROLS
=========================================== */
// Opening the chatbot widget
window.chatbot.openWidget()
.then(response => {
console.log("Widget opened:", response);
})
.catch(error => {
console.error("Error opening widget:", error);
});
// Closing the chatbot widget
window.chatbot.closeWidget()
.then(response => {
console.log("Widget closed:", response);
})
.catch(error => {
console.error("Error closing widget:", error);
});
// Toggling the chatbot widget (open if closed, close if open)
window.chatbot.toggleWidget()
.then(response => {
console.log("Widget toggled:", response);
})
.catch(error => {
console.error("Error toggling widget:", error);
});
// Setting the chatbot theme to light mode
window.chatbot.setTheme('light')
.then(response => {
console.log("Theme set to light:", response);
})
.catch(error => {
console.error("Error setting theme:", error);
});
// Setting the chatbot theme to dark mode
window.chatbot.setTheme('dark')
.then(response => {
console.log("Theme set to dark:", response);
})
.catch(error => {
console.error("Error setting theme:", error);
});
// Toggling the chatbot theme (light to dark or dark to light)
window.chatbot.toggleTheme()
.then(response => {
console.log("Theme toggled:", response);
})
.catch(error => {
console.error("Error toggling theme:", error);
});
/* ===========================================
4. EVENT LISTENERS
=========================================== */
// 1. Chat messages
const chatHandler = function(data) {
console.log("Chat event received:", data);
// Handle new chat messages from the chatbot
};
window.chatbot.addEventListener("chat", chatHandler);
// 2. Lead submissions
const leadSubmissionHandler = function(data) {
console.log("Lead submission received:", data);
// Handle when a user submits a lead form in the chatbot
};
window.chatbot.addEventListener("lead-submission", leadSubmissionHandler);
// 3. Live chat escalation
const liveChatEscalationHandler = function(data) {
console.log("Live chat escalation requested:", data);
// Handle when user requests to speak with a human agent
};
window.chatbot.addEventListener("live-chat-escalation", liveChatEscalationHandler);
// 4. Widget minimization
const minimizeWidgetHandler = function(data) {
console.log("Widget minimized:", data);
// Handle when user minimizes the chat widget
};
window.chatbot.addEventListener("minimize-widget", minimizeWidgetHandler);
// Removing event listeners
window.chatbot.removeEventListener("chat", chatHandler);
/* ===========================================
5. CONFIGURATION
=========================================== */
// Get current configuration
const config = window.chatbot.getConfig();
console.log("Current configuration:", config);
/* ===========================================
6. ERROR HANDLING
=========================================== */
// Option 1: Using try-catch blocks
try {
window.chatbot.sendUserInfo({
name: "John Doe",
info: "Basic plan user"
});
} catch (error) {
console.error("Error using SDK:", error);
}
// Option 2: Using Promise error handling
window.chatbot.sendUserInfo({
email: "[email protected]",
phone: "555-123-4567",
info: "Last visited: " + new Date().toLocaleDateString()
})
.then(response => {
// Success handler
})
.catch(error => {
// Error handler
})
.finally(() => {
// Always executed
});
/* ===========================================
7. COMMON USAGE PATTERNS
=========================================== */
// Sending user data after login
function onUserLogin(userData) {
if (window.chatbot) {
window.chatbot.sendUserInfo({
userId: userData.id || userData.userId,
userHash: userData.securityHash || userData.userHash,
name: userData.displayName,
email: userData.email,
phone: userData.phoneNumber,
info: userData.accountType || "Standard user"
}).then(() => {
console.log("User info sent to chatbot after login");
});
}
}
// Setting up all event listeners at once
function setupChatbotEventListeners() {
const events = ["chat", "lead-submission", "live-chat-escalation", "minimize-widget"];
events.forEach(eventName => {
window.chatbot.addEventListener(eventName, function(data) {
console.log(`${eventName} event received:`, data);
// Process event data as needed
});
});
}
// Widget control examples
function openChatWidget() {
if (window.chatbot) {
window.chatbot.openWidget()
.then(() => {
console.log("Chat widget opened successfully");
})
.catch(error => {
console.error("Failed to open chat widget:", error);
});
}
}
function closeChatWidget() {
if (window.chatbot) {
window.chatbot.closeWidget()
.then(() => {
console.log("Chat widget closed successfully");
})
.catch(error => {
console.error("Failed to close chat widget:", error);
});
}
}
function toggleChatWidget() {
if (window.chatbot) {
window.chatbot.toggleWidget()
.then(() => {
console.log("Chat widget toggled successfully");
})
.catch(error => {
console.error("Failed to toggle chat widget:", error);
});
}
}
// Theme control examples
function setLightTheme() {
if (window.chatbot) {
window.chatbot.setTheme('light')
.then(() => {
console.log("Theme set to light successfully");
})
.catch(error => {
console.error("Failed to set light theme:", error);
});
}
}
function setDarkTheme() {
if (window.chatbot) {
window.chatbot.setTheme('dark')
.then(() => {
console.log("Theme set to dark successfully");
})
.catch(error => {
console.error("Failed to set dark theme:", error);
});
}
}
function toggleChatTheme() {
if (window.chatbot) {
window.chatbot.toggleTheme()
.then(() => {
console.log("Chat theme toggled successfully");
})
.catch(error => {
console.error("Failed to toggle chat theme:", error);
});
}
}
// Conditional widget control based on user behavior
function handleUserAction(action) {
if (action === 'help-needed') {
// Open widget when user needs help
window.chatbot.openWidget();
} else if (action === 'completed-task') {
// Close widget when user completes their task
window.chatbot.closeWidget();
}
}
// Dynamic theme switching based on user preferences or time of day
function setThemeBasedOnUserPreference(userPreference) {
const theme = userPreference === 'dark' ? 'dark' : 'light';
window.chatbot.setTheme(theme);
}
function setThemeBasedOnTimeOfDay() {
const currentHour = new Date().getHours();
const isDayTime = currentHour >= 6 && currentHour < 18;
const theme = isDayTime ? 'light' : 'dark';
window.chatbot.setTheme(theme);
}