Complete example showcasing programmatic messaging, event handling, API integration, and all advanced features.
The configuration panel above is a powerful testing console with four main tabs:
Edit JSON configuration in real-time with:
Comprehensive testing tools:
Monitor widget activity:
Quick configuration presets:
Open the Testing Suite tab in the config panel above and try these scenarios:
Run from console: tester.runScenario('quick-test')
Sends a few basic messages to verify the widget is working.
Run from console: tester.runScenario('e-commerce-flow')
Simulates a complete order support conversation with tracking information.
Run from console: tester.runScenario('support-escalation')
Demonstrates gathering information and escalating to technical support.
Run from console: tester.runScenario('error-handling')
Shows how to handle errors gracefully with retry logic.
Run from console: tester.runScenario('long-conversation')
Tests scrolling and performance with a long message history.
Run from console: tester.runScenario('rapid-fire')
Stress tests the widget with rapidly sent messages.
// Send a simple message
window.chatBox.sendToWidget({
type: 'new-message',
data: {
text: 'Hello! How can I help you?',
sender: 'agent',
timestamp: new Date().toISOString()
}
});
// Send a message with quick reply suggestions
window.chatBox.sendToWidget({
type: 'new-message',
data: {
text: 'What would you like help with?',
sender: 'agent',
timestamp: new Date().toISOString(),
suggestions: ['Technical Support', 'Billing', 'General Question']
}
});
// Available via the testing utilities
window.tester.sendTemplateMessage('welcome-personalized', {
name: 'John Doe'
});
window.tester.sendTemplateMessage('order-status', {
orderId: 'ORD-12345',
status: 'shipped'
});
// Listen for widget events
window.chatBox.on('open', () => {
console.log('Widget opened');
});
window.chatBox.on('close', () => {
console.log('Widget closed');
});
window.chatBox.on('message', (data) => {
console.log('Message received:', data);
// Auto-respond to user messages
if (data.sender === 'user') {
setTimeout(() => {
window.chatBox.sendToWidget({
type: 'new-message',
data: {
text: 'Thanks for your message! Let me help you with that.',
sender: 'agent',
timestamp: new Date().toISOString()
}
});
}, 1000);
}
});
window.chatBox.on('error', (error) => {
console.error('Widget error:', error);
});
// Update theme colors dynamically
window.chatBox.updateTheme({
primaryColor: '#28a745',
secondaryColor: '#1e7e34'
});
// Toggle dark mode
window.chatBox.updateTheme({
darkMode: true,
backgroundColor: '#1e1e1e',
textColor: '#ffffff'
});
// Reset to light theme
window.chatBox.updateTheme({
darkMode: false,
backgroundColor: '#ffffff',
textColor: '#333333'
});
// Programmatically open the widget window.chatBox.open(); // Close the widget window.chatBox.close(); // Toggle widget state window.chatBox.toggle(); // Destroy widget instance (cleanup) window.chatBox.destroy();
const chatBox = new ChatBoxSDK({
// API Configuration
apiKey: 'your-api-key',
apiEndpoint: 'https://api.example.com/chat',
// User Identification
userId: 'user-67890',
userMetadata: {
name: 'Jane Smith',
email: 'jane@company.com',
avatar: 'https://i.pravatar.cc/150?img=5',
customFields: {
plan: 'enterprise',
seats: 50,
billingStatus: 'active',
accountAge: 365,
mrr: 499.00,
tags: ['vip', 'enterprise', 'priority']
}
},
// Context Data
context: {
page: 'dashboard',
feature: 'analytics',
lastLogin: new Date().toISOString(),
subscription: 'active',
referrer: document.referrer,
// Any custom context your backend needs
customContext: {
projectId: 'proj-123',
teamSize: 10,
industry: 'SaaS'
}
},
// Theme Customization
theme: {
primaryColor: '#6f42c1',
secondaryColor: '#5a32a3',
backgroundColor: '#ffffff',
textColor: '#333333',
borderRadius: '8px',
fontFamily: 'Inter, -apple-system, sans-serif',
shadows: true,
darkMode: false
},
// UI Text
ui: {
title: 'Enterprise Support',
subtitle: 'Priority support - Response time: <5min',
placeholder: 'How can we help you today?',
sendButtonText: 'Send',
minimizeButtonLabel: 'Minimize',
closeButtonLabel: 'Close'
},
// Layout
layout: {
type: 'popup', // 'popup' or 'embedded'
position: 'bottom-right', // 'bottom-right', 'bottom-left', 'top-right', 'top-left'
width: '380px',
height: '600px',
zIndex: 9999
},
// Behavior
behavior: {
autoOpen: false,
rememberState: true,
showUnreadCount: true,
typingIndicator: true,
timestamps: true,
soundEnabled: true,
desktopNotifications: false
},
// Advanced Options
advanced: {
enableLogging: true,
logLevel: 'info', // 'debug', 'info', 'warn', 'error'
sessionTimeout: 3600000, // 1 hour in ms
retryAttempts: 3,
retryDelay: 1000
}
});
// Setup comprehensive event handling
chatBox.on('ready', () => {
console.log('โ
Widget ready');
});
chatBox.on('open', () => {
console.log('Widget opened');
// Track analytics
analytics.track('chat_opened');
});
chatBox.on('close', () => {
console.log('Widget closed');
analytics.track('chat_closed');
});
chatBox.on('message', (data) => {
console.log('Message:', data);
// Log user messages to analytics
if (data.sender === 'user') {
analytics.track('message_sent', {
messageLength: data.text.length
});
}
});
chatBox.on('error', (error) => {
console.error('Error:', error);
// Report to error tracking service
Sentry.captureException(error);
});
Use the built-in testing utilities to benchmark widget performance:
// Run stress test (send 100 messages)
const result = await ChatBoxTestUtils.stressTest(window.chatBox, 100);
console.log('Stress test results:', result);
// Output: { messageCount, duration, messagesPerSecond, errors }
// Test all API methods
const apiTest = ChatBoxTestUtils.testAPI(window.chatBox);
console.log('API test results:', apiTest);
// Output: { total, passed, failed, tests: [...] }
// Benchmark initialization time
const benchmark = await ChatBoxTestUtils.benchmarkInit(
() => ({ apiKey: 'test' }),
5 // iterations
);
console.log('Benchmark results:', benchmark);
// Output: { iterations, times, average, min, max }
window.chatBoxConfigPanel, window.chatBox, and window.tester to
access the full API interactively.
Example of integrating with your backend API:
// Backend API endpoint configuration
const chatBox = new ChatBoxSDK({
apiKey: 'your-api-key',
apiEndpoint: 'https://api.example.com/chat',
// These will be sent with each request
userId: 'user-123',
context: {
page: 'support',
ticketId: 'TKT-5678'
}
});
// Your backend should respond with this format:
// {
// "message": "This is the bot's response",
// "sessionId": "session_123abc",
// "timestamp": "2024-01-01T12:00:00Z",
// "metadata": {
// "messageCount": 5,
// "suggestions": ["Tell me more", "Contact support", "End chat"]
// }
// }