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:

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:

bash
npm install @konpro/avatar-widget

Basic Usage

Secure Implementation (Recommended)

This is the recommended approach for production. Create a backend endpoint to generate session tokens securely.

Backend - Generate Session Token

javascript
// 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

html
<!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.

html
<!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.

jsx
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:

OptionTypeDefaultDescription
sessionTokenstringrequired*Session token from backend (recommended)
apiKeystringrequired*Your KonPro API key (⚠️ dev only - not secure)
agenticAvatarIdstringrequiredID of the agentic avatar to use
containerIdstringkonpro-avatarID of the container element
positionstringbottom-rightWidget position: bottom-right, bottom-left, top-right, top-left, center
themestringlightTheme: light, dark, auto
languagestringenLanguage code
autoOpenbooleanfalseAuto-open widget on load
widthstring400pxWidget width
heightstring600pxWidget height
zIndexnumber9999Widget z-index
customStylesobjectCustom CSS styles

*Use either sessionToken (secure) OR apiKey (development only), not both.

Widget API Methods

Control the widget programmatically using these methods:

javascript
// 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:

javascript
// 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:

javascript
// 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 HandlerDescriptionEvent Data
onReadyFired when widget is fully initialized and readyNone
onOpenFired when widget is openedNone
onCloseFired when widget is closedNone
onMessageFired when a message is received{type, content, timestamp}
onErrorFired when an error occurs{message, code}
onSessionStartFired when a session starts{id, timestamp}
onSessionEndFired when a session endsNone
onCustomEventFired for custom events from the widget{eventName, eventData}

Use Cases

  • Analytics Integration: Track widget interactions and user engagement using onOpen, onClose, and onMessage events.
  • Error Handling: Use onError to display user-friendly error messages or log errors to your error tracking service.
  • Session Management: Track session lifecycle with onSessionStart and onSessionEnd for analytics or billing purposes.
  • Custom UI Updates: Use onCustomEvent to update your application UI based on widget state changes (e.g., typing indicators, file uploads).
  • Message Processing: Use onMessage to process and store conversations, integrate with your backend, or trigger workflows.

Advanced Widget Features

Custom Styling

Customize the widget appearance with custom styles:

javascript
// 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_domains when 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.

Table of Contents