Knapsack

Widget Integration

Learn how to embed Knapsack as a component in your application

Widget Integration

Integrate the Knapsack chatbot directly into your web application as either a floating widget or an embedded component.

Installation

npm install @knapsack/widget
yarn add @knapsack/widget
<script src="https://cdn.knapsack.ai/widget/latest/knapsack-widget.umd.js"></script>
<link rel="stylesheet" href="https://cdn.knapsack.ai/widget/latest/knapsack-widget.css">

Quick Start

Floating Widget

The floating widget appears as a chat bubble in the corner of your page:

import KnapsackWidget from '@knapsack/widget';

// Initialize the widget
const widget = await KnapsackWidget.init({
  container: '#knapsack-widget',
  mode: 'floating',
  position: 'bottom-right',
  theme: 'light',
  accessToken: 'your-access-token',
  user: {
    email: 'user@example.com',
    name: 'John Doe'
  }
});

Embedded Component

Embed the chatbot directly into your page layout:

import KnapsackWidget from '@knapsack/widget';

// Initialize as embedded component
const widget = await KnapsackWidget.init({
  container: '#knapsack-widget',
  mode: 'embedded',
  width: '100%',
  height: '600px',
  theme: 'light',
  accessToken: 'your-access-token'
});

Configuration Options

Basic Options

OptionTypeDefaultDescription
containerstring | HTMLElementrequiredContainer element or selector
mode'floating' | 'embedded''floating'Display mode
theme'light' | 'dark''light'Color theme
accessTokenstringundefinedUser authentication token
userobjectundefinedUser information

Styling Options

Customize the appearance of the widget:

const widget = await KnapsackWidget.init({
  container: '#knapsack-widget',
  mode: 'floating',

  // Floating mode styling
  position: 'bottom-right', // or 'bottom-left', 'top-right', 'top-left'
  circleColor: '#FF8435',   // Custom bubble color
  circleSize: 60,           // Bubble size in pixels
  expandedWidth: '800px',   // Width when expanded

  // Embedded mode styling
  width: '100%',
  height: '600px',
  borderRadius: '8px',

  // General styling
  primaryColor: '#FF8435',  // Brand color
  fontFamily: 'system-ui, sans-serif'
});

Floating Widget Positioning

// Use preset positions
position: 'bottom-right'  // bottom-right, bottom-left, top-right, top-left
// Use custom coordinates
position: { x: 20, y: 20 }  // 20px from left, 20px from top

React Integration

For React applications, wrap the widget in a component:

import { useEffect, useRef } from 'react';
import KnapsackWidget from '@knapsack/widget';

function KnapsackChat({ accessToken, user }) {
  const containerRef = useRef<HTMLDivElement>(null);
  const widgetRef = useRef<any>(null);

  useEffect(() => {
    if (!containerRef.current) return;

    // Initialize widget
    KnapsackWidget.init({
      container: containerRef.current,
      mode: 'embedded',
      width: '100%',
      height: '600px',
      accessToken,
      user,
      primaryColor: '#FF8435'
    }).then(widget => {
      widgetRef.current = widget;
    });

    // Cleanup on unmount
    return () => {
      if (widgetRef.current) {
        widgetRef.current.destroy();
      }
    };
  }, [accessToken, user]);

  return <div ref={containerRef} />;
}

Authentication

The widget supports multiple authentication methods:

// Exchange your Auth0 token for an internal Knapsack token
const response = await fetch('https://api.knapsack.ai/api/auth/auth0/signin', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    access_token: yourAuth0Token,
    user: {
      email: 'user@example.com',
      name: 'John Doe',
      sub: 'auth0|123456'
    },
    login_provider: 'google', // or 'microsoft'
    platform: 'web'
  })
});

const { access_token } = await response.json();

// Use the internal token
const widget = await KnapsackWidget.init({
  container: '#knapsack-widget',
  accessToken: access_token,
  user: { email: 'user@example.com', name: 'John Doe' },
  loginProvider: 'google'
});

Direct Auth0 Token

const widget = await KnapsackWidget.init({
  container: '#knapsack-widget',
  accessToken: yourAuth0Token,
  user: { email: 'user@example.com', name: 'John Doe' },
  loginProvider: 'google'
});

The widget will automatically exchange Auth0 tokens for internal tokens when needed.

Methods

Widget Instance Methods

// Show/hide widget
widget.show();
widget.hide();

// For floating widgets
widget.expand();    // Open the chat
widget.collapse();  // Close the chat
widget.toggle();    // Toggle open/closed
widget.isExpanded(); // Check if expanded

// Send a message programmatically
widget.sendMessage('Hello, Knapsack!');

// Get conversation history
const history = widget.getConversationHistory();

// Update configuration
widget.update({
  theme: 'dark',
  primaryColor: '#0066CC'
});

// Destroy widget
widget.destroy();

Events

Listen to widget events:

const widget = await KnapsackWidget.init({
  container: '#knapsack-widget',
  onReady: () => {
    console.log('Widget is ready');
  },
  onError: (error) => {
    console.error('Widget error:', error);
  },
  onEvent: (event) => {
    switch (event.type) {
      case 'message_sent':
        console.log('User sent:', event.data);
        break;
      case 'message_received':
        console.log('AI responded:', event.data);
        break;
      case 'conversation_started':
        console.log('New conversation started');
        break;
    }
  }
});

Full Example

Here's a complete implementation example:

<!DOCTYPE html>
<html>
<head>
  <title>Knapsack Widget Demo</title>
  <link rel="stylesheet" href="https://cdn.knapsack.ai/widget/latest/knapsack-widget.css">
</head>
<body>
  <div id="knapsack-widget"></div>

  <script src="https://cdn.knapsack.ai/widget/latest/knapsack-widget.umd.js"></script>
  <script>
    // Initialize the widget
    (async () => {
      const widget = await KnapsackWidget.init({
        container: '#knapsack-widget',
        mode: 'floating',
        position: 'bottom-right',
        theme: 'light',
        circleColor: '#FF8435',
        circleSize: 60,
        expandedWidth: '800px',
        primaryColor: '#FF8435',

        // Authentication
        accessToken: 'your-access-token',
        user: {
          email: 'user@example.com',
          name: 'John Doe'
        },
        loginProvider: 'google',

        // Callbacks
        onReady: () => {
          console.log('Knapsack widget is ready!');
        },
        onError: (error) => {
          console.error('Widget error:', error);
        }
      });

      console.log('Widget initialized:', widget);
    })();
  </script>
</body>
</html>

Styling Customization

CSS Variables

Override CSS variables to match your brand:

#knapsack-widget {
  --knapsack-primary-color: #FF8435;
  --knapsack-background: #ffffff;
  --knapsack-text-color: #000000;
  --knapsack-border-radius: 12px;
  --knapsack-font-family: system-ui, -apple-system, sans-serif;
}

Custom Styles

Apply custom styles to override defaults:

/* Customize the floating bubble */
.knapsack-floating-widget-circle {
  box-shadow: 0 4px 12px rgba(255, 132, 53, 0.3) !important;
}

/* Customize the expanded chat */
.knapsack-floating-widget-expanded {
  border: 2px solid #FF8435 !important;
}

/* Customize the input */
.knapsack-chat-input {
  border-color: #FF8435 !important;
}

Troubleshooting

Widget Not Appearing

  1. Check that the container element exists
  2. Verify authentication credentials
  3. Check browser console for errors
  4. Ensure CSS is loaded

Authentication Issues

  1. Verify access token is valid
  2. Check user object contains required fields
  3. Ensure login provider matches token issuer

Styling Issues

  1. Check CSS specificity
  2. Verify CSS variables are applied correctly
  3. Use browser DevTools to inspect styles

Next Steps