Widget Integration
Embed an interactive AI avatar directly into your website or application using the KonPro widget.
⚠️ Important Security Notice
- • Never use your API key directly in client-side code - This exposes your key to anyone who views your page source
- • API keys in JavaScript are NOT secure and not recommended for production
- • Always use server-side session tokens for widget authentication in production environments
For production deployments, create a backend endpoint that generates session tokens, call it from your frontend, and use the session token to initialize the widget. Never expose your actual API key to the client.
Installation
Method 1: Script Tag
Add the following script to your HTML:
<!-- Add to the <head> section or before closing </body> tag -->
<script src="https://cdn.konpro.ai/v1/widget.min.js"></script>Method 2: NPM Package
Install the widget package via npm:
npm install @konpro/avatar-widgetBasic Usage
Secure Implementation (Recommended)
This is the recommended approach for production. Create a backend endpoint to generate session tokens securely.
Backend - Generate Session Token
// backend/api.js (Node.js example)
app.post('/api/widget-session', authenticateUser, async (req, res) => {
const response = await fetch('https://api.konpro.ai/v1/widget/sessions', {
method: 'POST',
headers: {
'x-api-key': process.env.KONPRO_API_KEY, // Secure server-side
'Content-Type': 'application/json'
},
body: JSON.stringify({
agentic_avatar_id: req.body.avatarId,
settings: {
max_duration: 3600,
allowed_domains: ['yourdomain.com']
}
})
});
const data = await response.json();
res.json({ sessionToken: data.session_token });
});Frontend - Use Session Token
<!DOCTYPE html>
<html>
<head>
<title>KonPro Avatar Widget - Secure Implementation</title>
<script src="https://cdn.konpro.ai/v1/widget.min.js"></script>
</head>
<body>
<div id="konpro-avatar"></div>
<script>
// Fetch session token from your backend
async function initializeWidget() {
try {
// Call YOUR backend endpoint (not KonPro directly)
const response = await fetch('/api/widget-session', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
avatarId: 'YOUR_AGENTIC_AVATAR_ID'
})
});
const { sessionToken } = await response.json();
// Initialize widget with session token
KonproWidget.init({
containerId: 'konpro-avatar',
sessionToken: sessionToken, // Use session token, NOT API key
config: {
position: 'bottom-right',
theme: 'light',
language: 'en',
autoOpen: false
}
});
} catch (error) {
console.error('Failed to initialize widget:', error);
}
}
initializeWidget();
</script>
</body>
</html>Development/Testing Only (Not Secure)
⚠️ Warning: This method exposes your API key and should ONLY be used for local development/testing.
<!DOCTYPE html>
<html>
<head>
<title>KonPro Avatar Widget - Development Only</title>
<script src="https://cdn.konpro.ai/v1/widget.min.js"></script>
</head>
<body>
<div id="konpro-avatar"></div>
<script>
// ⚠️ NEVER DO THIS IN PRODUCTION - API KEY EXPOSED
KonproWidget.init({
containerId: 'konpro-avatar',
apiKey: 'YOUR_API_KEY', // NOT SECURE - Development only
agenticAvatarId: 'YOUR_AGENTIC_AVATAR_ID',
config: {
position: 'bottom-right',
theme: 'light',
language: 'en',
autoOpen: false
}
});
</script>
</body>
</html>React Integration (Secure)
Integrate the widget into your React application using the secure session token method.
import React, { useEffect, useState } from 'react';
import KonproWidget from '@konpro/avatar-widget';
function App() {
const [isWidgetReady, setIsWidgetReady] = useState(false);
useEffect(() => {
async function setupWidget() {
try {
// Fetch session token from your backend
const response = await fetch('/api/widget-session', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// Include your auth headers if needed
'Authorization': `Bearer ${userAuthToken}`
},
body: JSON.stringify({
avatarId: 'YOUR_AGENTIC_AVATAR_ID'
})
});
const { sessionToken } = await response.json();
// Initialize widget with session token
const widget = new KonproWidget({
sessionToken: sessionToken, // Secure: using session token
config: {
position: 'bottom-right',
theme: 'light'
}
});
widget.mount('#konpro-avatar');
setIsWidgetReady(true);
return () => {
widget.destroy();
};
} catch (error) {
console.error('Failed to initialize widget:', error);
}
}
setupWidget();
}, []);
return (
<div>
<div id="konpro-avatar"></div>
{!isWidgetReady && <p>Loading avatar...</p>}
</div>
);
}Widget Configuration
Configure the widget behavior and appearance using these options:
| Option | Type | Default | Description |
|---|---|---|---|
| sessionToken | string | required* | Session token from backend (recommended) |
| apiKey | string | required* | Your KonPro API key (⚠️ dev only - not secure) |
| agenticAvatarId | string | required | ID of the agentic avatar to use |
| containerId | string | konpro-avatar | ID of the container element |
| position | string | bottom-right | Widget position: bottom-right, bottom-left, top-right, top-left, center |
| theme | string | light | Theme: light, dark, auto |
| language | string | en | Language code |
| autoOpen | boolean | false | Auto-open widget on load |
| width | string | 400px | Widget width |
| height | string | 600px | Widget height |
| zIndex | number | 9999 | Widget z-index |
| customStyles | object | Custom CSS styles |
*Use either sessionToken (secure) OR apiKey (development only), not both.
Widget API Methods
Control the widget programmatically using these methods:
// Initialize Widget
KonproWidget.init(config);
// Open Widget
KonproWidget.open();
// Close Widget
KonproWidget.close();
// Toggle Widget
KonproWidget.toggle();
// Send Message
KonproWidget.sendMessage('Hello, how are you?');
// Update Configuration
KonproWidget.updateConfig({
theme: 'dark',
language: 'es'
});
// Destroy Widget
KonproWidget.destroy();
// Check if widget is open
const isOpen = KonproWidget.isOpen();
// Get current session info
const session = KonproWidget.getSession();
// Clear conversation history
KonproWidget.clearHistory();
// Set custom metadata
KonproWidget.setMetadata({
userId: 'user-123',
userName: 'John Doe',
context: 'support'
});Widget Events
Listen to widget events to respond to user interactions:
// Widget opened
KonproWidget.on('open', () => {
console.log('Widget opened');
});
// Widget closed
KonproWidget.on('close', () => {
console.log('Widget closed');
});
// Message received
KonproWidget.on('message', (data) => {
console.log('Message received:', data.message);
});
// Error occurred
KonproWidget.on('error', (error) => {
console.error('Widget error:', error);
});
// Session started
KonproWidget.on('session:start', (session) => {
console.log('Session started:', session.id);
});
// Session ended
KonproWidget.on('session:end', () => {
console.log('Session ended');
});Widget with Custom Events
The widget supports custom event handlers that allow you to integrate deeply with your application. You can pass event handlers during initialization or register them after the widget is ready.
Custom Event Handlers
Custom events enable you to track user interactions, handle specific widget states, and integrate with your analytics or business logic. You can define event handlers during widget initialization or add them dynamically.
Initialization with Custom Events
Pass event handlers directly when initializing the widget:
// Initialize widget with custom event handlers
KonproWidget.init({
sessionToken: sessionToken,
config: {
position: 'bottom-right',
theme: 'light'
},
onReady: () => {
console.log('Widget is ready');
// Widget is initialized and ready
},
onOpen: () => {
console.log('Widget opened');
// Track widget open event
analytics.track('widget_opened');
},
onClose: () => {
console.log('Widget closed');
// Track widget close event
analytics.track('widget_closed');
},
onMessage: (data) => {
console.log('Message received:', data);
// Handle incoming messages
if (data.type === 'user_message') {
// Process user message
handleUserMessage(data.content);
} else if (data.type === 'avatar_response') {
// Process avatar response
handleAvatarResponse(data.content);
}
},
onError: (error) => {
console.error('Widget error:', error);
// Handle errors
showErrorNotification(error.message);
},
onSessionStart: (session) => {
console.log('Session started:', session.id);
// Track session start
trackSessionStart(session);
},
onSessionEnd: () => {
console.log('Session ended');
// Track session end
trackSessionEnd();
},
onCustomEvent: (eventName, eventData) => {
console.log('Custom event:', eventName, eventData);
// Handle custom events
switch (eventName) {
case 'user_typing':
showTypingIndicator();
break;
case 'avatar_thinking':
showThinkingIndicator();
break;
case 'file_uploaded':
handleFileUpload(eventData);
break;
default:
console.log('Unknown custom event:', eventName);
}
}
});
// You can also register event listeners after initialization
KonproWidget.on('custom:user_action', (data) => {
console.log('User action:', data);
// Handle custom user actions
});
KonproWidget.on('custom:avatar_emotion', (emotion) => {
console.log('Avatar emotion:', emotion);
// Update UI based on avatar emotion
updateAvatarEmotion(emotion);
});Available Custom Event Types
| Event Handler | Description | Event Data |
|---|---|---|
| onReady | Fired when widget is fully initialized and ready | None |
| onOpen | Fired when widget is opened | None |
| onClose | Fired when widget is closed | None |
| onMessage | Fired when a message is received | {type, content, timestamp} |
| onError | Fired when an error occurs | {message, code} |
| onSessionStart | Fired when a session starts | {id, timestamp} |
| onSessionEnd | Fired when a session ends | None |
| onCustomEvent | Fired for custom events from the widget | {eventName, eventData} |
Use Cases
- Analytics Integration: Track widget interactions and user engagement using
onOpen,onClose, andonMessageevents. - Error Handling: Use
onErrorto display user-friendly error messages or log errors to your error tracking service. - Session Management: Track session lifecycle with
onSessionStartandonSessionEndfor analytics or billing purposes. - Custom UI Updates: Use
onCustomEventto update your application UI based on widget state changes (e.g., typing indicators, file uploads). - Message Processing: Use
onMessageto process and store conversations, integrate with your backend, or trigger workflows.
Advanced Widget Features
Custom Styling
Customize the widget appearance with custom styles:
// Custom Styling
KonproWidget.init({
sessionToken: sessionToken, // Secure method
config: {
customStyles: {
primaryColor: '#007bff',
fontFamily: 'Arial, sans-serif',
borderRadius: '12px',
boxShadow: '0 4px 6px rgba(0,0,0,0.1)'
}
}
});
// Webhook Integration
KonproWidget.init({
sessionToken: sessionToken, // Secure method
config: {
webhooks: {
onMessage: 'https://your-server.com/webhook/message',
onSession: 'https://your-server.com/webhook/session'
}
}
});Notes
- Always use session tokens in production - never expose your API key in client-side code.
- Session tokens are generated using the Create Widget Session endpoint.
- Configure
allowed_domainswhen creating sessions to restrict widget usage to specific domains. - The widget supports both voice and text input, configurable via session settings.
- Use widget events to track user interactions and integrate with your analytics.
- For more information about widget sessions, see Create Widget Session, Get Widget Session, and Delete Widget Session.