We're still building things here! Help us improve by reporting bugs here.

Advanced Usage

Advanced features, customizations, and integrations for power users.

Programmatic API

The widget exposes a global CompaninWidget object for programmatic control. This allows you to integrate the widget deeply into your application's user experience, triggering widget actions based on user behavior or application state.

The API is loaded asynchronously, so always check if it exists before calling methods. You can also listen for a custom event when it's ready.

Available Methods

These methods give you full programmatic control over the widget's visibility and behavior.

<script id="companin-widget-script-sales" src="https://widget.companin.tech/widget.js" data-client-id="YOUR_CLIENT_ID" data-assistant-id="YOUR_ASSISTANT_ID" data-config-id="YOUR_CONFIG_ID" data-instance-id="sales-widget"></script><script>  // Ensure the widget has loaded before calling methods  window.addEventListener('load', () => {    const salesWidget = window.CompaninWidgets?.get('sales-widget') || window.CompaninWidget;    if (salesWidget) {      salesWidget.show();      salesWidget.sendMessage && salesWidget.sendMessage('Hello from page');    }  });</script>

Event Listening

Listen for widget events using the postMessage API. This is perfect for tracking user engagement, triggering application logic based on widget interactions, or syncing widget state with your application.

Common use cases:

  • Track widget engagement in your analytics platform
  • Show contextual help based on widget conversations
  • Trigger application actions when conversations start
  • Update UI elements based on widget state
  • Record customer support interactions in your CRM
<script>window.addEventListener('message', (event) => {  if (event.origin !== 'https://widget.companin.tech') return;  const { type, data } = event.data || {};  switch (type) {    case 'WIDGET_READY':      console.log('Widget is ready');      break;    case 'WIDGET_OPENED':      console.log('Widget was opened');      break;    case 'MESSAGE_SENT':      console.log('User sent message:', data?.message);      break;  }});</script>

Custom Styling

While the configuration interface provides extensive styling options, you can go even further with custom CSS for advanced customizations. This is useful when you need unique visual effects, animations, or styles that aren't available in the standard configuration.

Important considerations:

  • Custom styles override configuration settings
  • Use !important sparingly—only when necessary to override iframe isolation
  • Test thoroughly across browsers as custom CSS may behave differently
  • Widget updates might affect your custom styles—review after each update

CSS Overrides

Target widget elements using the container class. Add your custom CSS either in the widget configuration's custom CSS field or in your site's global stylesheet:

/* Target the widget container */.companin-widget-container {  /* Custom styles */}/* Style the collapsed button */.companin-widget-container button {  border-radius: 50% !important;  box-shadow: 0 0 20px rgba(0, 0, 0, 0.3) !important;}/* Custom message bubble styles */.companin-widget-container .message-bubble {  background: linear-gradient(45deg, #667eea 0%, #764ba2 100%) !important;}/* Hide the default close button */.companin-widget-container .close-button {  display: none !important;}

Theme Customization

Advanced theming with CSS custom properties:

:root {  /* Override widget theme variables */  --companin-primary: #ff6b6b;  --companin-secondary: #4ecdc4;  --companin-background: #2d3748;  --companin-text: #e2e8f0;  --companin-border-radius: 12px;}/* Dark theme variant */@media (prefers-color-scheme: dark) {  :root {    --companin-background: #1a202c;    --companin-text: #f7fafc;  }}

Analytics Integration

Understanding how users interact with your widget is crucial for optimization. By integrating with your analytics platform, you can track engagement metrics, identify popular topics, and measure the widget's impact on user experience and conversion rates.

Key metrics to track:

  • Widget open/close rates
  • Messages sent per session
  • Average conversation length
  • Popular conversation topics (from flows)
  • Time to first message
  • Completion rates for conversation flows

Google Analytics

Track widget interactions as custom events in Google Analytics. This integrates seamlessly with your existing analytics setup:

// Track widget eventswindow.addEventListener('message', (event) => {  if (event.origin !== 'https://widget.companin.tech') return;  const { type, data } = event.data;  switch (type) {    case 'WIDGET_OPENED':      gtag('event', 'widget_opened', {        event_category: 'engagement',        event_label: 'chat_widget'      });      break;    case 'MESSAGE_SENT':      gtag('event', 'message_sent', {        event_category: 'engagement',        event_label: data.messageLength > 50 ? 'long_message' : 'short_message'      });      break;    case 'CONVERSATION_STARTED':      gtag('event', 'conversation_started', {        event_category: 'engagement',        event_label: 'chat_widget'      });      break;  }});

Custom Analytics

// Custom analytics trackingconst trackWidgetEvent = (eventName, properties = {}) => {  fetch('/api/analytics/track', {    method: 'POST',    headers: { 'Content-Type': 'application/json' },    body: JSON.stringify({      event: eventName,      properties: { widget: 'companin', ...properties }    })  });};window.addEventListener('message', (event) => {  if (event.origin !== 'https://widget.companin.tech') return;  const { type, data } = event.data;  switch (type) {    case 'WIDGET_OPENED':      trackWidgetEvent('widget_opened');      break;    case 'MESSAGE_SENT':      trackWidgetEvent('message_sent', { length: data.message?.length || 0 });      break;  }});

Webhook Integration

Webhooks provide real-time notifications when events occur in the widget. This enables powerful integrations with your backend systems, CRM, helpdesk software, or custom workflows.

Webhook benefits:

  • Real-time synchronization with your systems
  • Automatic ticket creation in support systems
  • Customer data enrichment in CRM
  • Automated workflow triggers
  • Compliance and audit logging

Event Webhooks

Configure webhook URLs in your dashboard to receive HTTP POST requests when specific events occur. Each webhook payload includes event data and metadata:

{  "event": "message_received",  "timestamp": "2024-01-09T10:30:00Z",  "data": {    "session_id": "sess_123456",    "message": {      "id": "msg_789",      "content": "Hello, I need help",      "sender": "user",      "timestamp": "2024-01-09T10:30:00Z"    },    "metadata": {      "user_agent": "Mozilla/5.0...",      "ip_address": "192.168.1.1",      "locale": "en"    }  }}

Available Events

  • widget_opened - User opened the widget
  • widget_closed - User closed the widget
  • conversation_started - New conversation initiated
  • message_received - User sent a message
  • message_sent - Assistant sent a message
  • flow_triggered - Conversation flow was activated
  • session_ended - Conversation session ended

Security Considerations

Security is paramount when embedding third-party content on your website. While the widget follows security best practices, there are additional steps you can take to harden your integration.

Content Security Policy (CSP)

Content Security Policy headers help prevent XSS attacks and other code injection vulnerabilities. Configure your CSP to explicitly allow the widget while maintaining strict security elsewhere:

# nginx.confadd_header Content-Security-Policy "  default-src 'self';  script-src 'self' https://widget.companin.tech;  style-src 'self' 'unsafe-inline' https://widget.companin.tech;  frame-src https://widget.companin.tech;  connect-src 'self' https://app.companin.tech;" always;

Input Validation

Always validate and sanitize user inputs:

// Validate message contentfunction validateMessage(message) {  if (message.length > 2000) {    return { valid: false, error: 'Message too long' };  }  const dangerousPatterns = [/<script/i, /javascript:/i, /onw+s*=/i];  for (const pattern of dangerousPatterns) {    if (pattern.test(message)) {      return { valid: false, error: 'Invalid content' };    }  }  return { valid: true };}const validation = validateMessage(userInput);if (!validation.valid) {  showError(validation.error);  return;}

Performance Optimization

The widget is optimized for performance out of the box, but there are strategies to make it even faster and more efficient, especially on high-traffic sites or slower connections.

Lazy Loading

Instead of loading the widget immediately when the page loads, defer it until the user needs it or after critical content has loaded. This improves your page's initial load time and Core Web Vitals scores:

// Load widget only when neededfunction loadWidget() {  if (window.CompaninWidget) return; // Already loaded  const script = document.createElement('script');  script.src = 'https://widget.companin.tech/widget.js';  script.setAttribute('data-client-id', 'YOUR_CLIENT_ID');  script.setAttribute('data-assistant-id', 'YOUR_ASSISTANT_ID');  script.setAttribute('data-config-id', 'YOUR_CONFIG_ID');  document.head.appendChild(script);}// Load on user interactiondocument.addEventListener('click', () => {  loadWidget();}, { once: true });// Or load after page loadwindow.addEventListener('load', () => {  setTimeout(loadWidget, 2000);});

Minimize custom CSS and imagesUse efficient color schemesLimit message history (configure in widget settings)Enable compression on your serverUse CDN for static assets

  • Minimize custom CSS and images
  • Use efficient color schemes
  • Limit message history (configure in widget settings)
  • Enable compression on your server
  • Use CDN for static assets

Accessibility Features

Keyboard Navigation

  • Tab - Navigate between elements
  • Enter / Space - Activate buttons
  • Escape - Close widget
  • Arrow keys - Navigate message history

Screen Reader Support

  • All interactive elements have proper ARIA labels
  • Message announcements for screen readers
  • Focus management when opening/closing
  • High contrast mode support

Color Contrast

Ensure your color choices meet WCAG guidelines:

  • Primary text: 4.5:1 contrast ratio minimum
  • Large text: 3:1 contrast ratio minimum
  • UI components: 3:1 contrast ratio minimum