API Overview

The SiteAssist widget exposes a simple JavaScript API that allows you to control the widget programmatically. All API methods are called through the global SiteAssist function.

window.SiteAssist(command, ...arguments);

Available Methods

init

Initializes the SiteAssist widget with your configuration.

Signature:

SiteAssist("init", options: InitOptions): void

Parameters:

  • options (object) - Configuration options

Example:

SiteAssist("init", {
  apiKey: "pk_live_abc123", // Your publishable key from dashboard
  type: "floating-bubble",
  theme: "auto",
});

See also: Configuration Guide for all available options.


open

Opens the chat widget.

Signature:

SiteAssist("open"): void

Example:

// Open the widget programmatically
SiteAssist("open");

Use cases:

  • Open widget when user clicks a custom button
  • Auto-open after a delay
  • Open based on user behavior or triggers

Example - Custom trigger button:

<button onclick="SiteAssist('open')">Need Help? Chat with AI</button>

Example - Auto-open after 5 seconds:

setTimeout(() => {
  SiteAssist("open");
}, 5000);

close

Closes the chat widget.

Signature:

SiteAssist("close"): void

Example:

// Close the widget programmatically
SiteAssist("close");

Use cases:

  • Close widget when user completes an action
  • Close on navigation to certain pages
  • Custom close triggers

Example - Close on page navigation:

// Close widget when navigating away
window.addEventListener("beforeunload", () => {
  SiteAssist("close");
});

toggle

Toggles the widget between open and closed states.

Signature:

SiteAssist("toggle"): void

Example:

// Toggle widget state
SiteAssist("toggle");

Use cases:

  • Custom toggle buttons in your UI
  • Keyboard shortcuts
  • Menu items

Example - Keyboard shortcut:

document.addEventListener("keydown", (e) => {
  // Ctrl/Cmd + K to toggle widget
  if ((e.ctrlKey || e.metaKey) && e.key === "k") {
    e.preventDefault();
    SiteAssist("toggle");
  }
});

changeTheme

Changes the widget theme dynamically.

Signature:

SiteAssist("changeTheme", theme: "light" | "dark" | "auto"): void

Parameters:

  • theme (string) - One of "light", "dark", or "auto"

Example:

// Change to dark theme
SiteAssist("changeTheme", "dark");

// Change to light theme
SiteAssist("changeTheme", "light");

// Change to auto (system preference)
SiteAssist("changeTheme", "auto");

Use cases:

  • Sync with your site's theme switcher
  • Match user preferences
  • Time-based theme switching

Example - Sync with site theme:

// When user changes site theme
function onSiteThemeChange(newTheme) {
  // Update site theme
  document.documentElement.setAttribute("data-theme", newTheme);

  // Update SiteAssist theme
  SiteAssist("changeTheme", newTheme);
}

Example - Theme toggle button:

<button id="theme-toggle">Toggle Theme</button>

<script>
  let currentTheme = "light";

  document.getElementById("theme-toggle").addEventListener("click", () => {
    currentTheme = currentTheme === "light" ? "dark" : "light";
    SiteAssist("changeTheme", currentTheme);
  });
</script>

track (Coming Soon)

Track custom events and analytics.

Signature:

SiteAssist("track", eventName: string, data?: any): void

Status: This feature is currently in development and will be available soon.

Planned usage:

// Once available, you'll be able to track events like this:

// Track a simple event
SiteAssist("track", "button_clicked");

// Track with additional data
SiteAssist("track", "product_viewed", {
  productId: "12345",
  productName: "Premium Widget",
  price: 99.99,
});

// E-commerce tracking
SiteAssist("track", "add_to_cart", {
  productId: "123",
  quantity: 1,
});

SiteAssist("track", "purchase_completed", {
  orderId: "ORD-123",
  total: 199.99,
});

identify (Coming Soon)

Identify users with additional information.

Signature:

SiteAssist("identify", user: {
  externalId?: string;
  email?: string;
  name?: string;
  attributes?: Record<string, string>;
}): void

Status: This feature is currently in development and will be available soon.

Planned usage:

// Once available, you'll be able to identify users like this:
SiteAssist("identify", {
  externalId: "user_123",
  email: "user@example.com",
  name: "John Doe",
  attributes: {
    plan: "premium",
    signupDate: "2024-01-15",
  },
});

Queuing Commands

The SiteAssist API supports command queuing, which means you can call API methods before the widget script has fully loaded. Commands will be executed in order once the script is ready.

Example:

// These commands will be queued and executed when ready
SiteAssist("init", { apiKey: "YOUR_API_KEY" });
SiteAssist("open");

This is handled automatically by the loader script:

!(function (t, e, c, n, s) {
  if (t[s]) return;
  const i = (t[s] = function () {
    i._q.push(arguments);
  });
  i._q = [];
  // ... loads actual script
})(window, document, 0, 0, "SiteAssist");

Custom Events

The widget dispatches custom events that you can listen to:

// Listen for custom widget events
window.addEventListener("sa:event_name", (event) => {
  console.log("Widget event:", event.detail);
});

Available Events:

Events are prefixed with sa: and include any custom events dispatched from the widget.

Example - Listen for custom events:

// Listen for all widget events
window.addEventListener("sa:chat_opened", () => {
  console.log("User opened the chat");
});

window.addEventListener("sa:message_sent", (event) => {
  console.log("User sent a message:", event.detail);
});

TypeScript Support

For TypeScript projects, you can add type definitions:

declare global {
  interface Window {
    SiteAssist: {
      (
        cmd: "init",
        opts: {
          apiKey: string;
          type?: "floating-bubble" | "sidepanel";
          theme?: "light" | "dark" | "auto";
          contentSelector?: boolean | string;
          externalId?: string;
          appContainerSelector?: string;
          widgetUrl?: string;
          apiUrl?: string;
        },
      ): void;
      (cmd: "open"): void;
      (cmd: "close"): void;
      (cmd: "toggle"): void;
      (cmd: "changeTheme", theme: "light" | "dark" | "auto"): void;
    };
  }
}

Usage:

// Now you get autocomplete and type checking
window.SiteAssist("init", {
  apiKey: "pk_live_abc123",
  theme: "dark", // TypeScript will validate this
});

// Open the widget
window.SiteAssist("open");

// Change theme
window.SiteAssist("changeTheme", "light");

Complete API Example

Here's a comprehensive example using multiple API methods:

// Initialize the widget
SiteAssist("init", {
  apiKey: "pk_live_abc123",
  type: "floating-bubble",
  theme: "auto",
});

// Auto-open after 10 seconds for first-time visitors
if (!localStorage.getItem("siteassist_visited")) {
  setTimeout(() => {
    SiteAssist("open");
  }, 10000);

  localStorage.setItem("siteassist_visited", "true");
}

// Sync theme with site theme switcher
document.getElementById("site-theme-toggle").addEventListener("click", (e) => {
  const newTheme = e.target.dataset.theme;
  SiteAssist("changeTheme", newTheme);
});

// Add custom help button
document.getElementById("help-button").addEventListener("click", () => {
  SiteAssist("open");
});

// Keyboard shortcut (Ctrl/Cmd + K)
document.addEventListener("keydown", (e) => {
  if ((e.ctrlKey || e.metaKey) && e.key === "k") {
    e.preventDefault();
    SiteAssist("toggle");
  }
});

Best Practices

1. Initialize Once

Only call init once per page load:

// ✅ Good
SiteAssist("init", { apiKey: "YOUR_API_KEY" });

// ❌ Avoid
SiteAssist("init", { apiKey: "YOUR_API_KEY" });
SiteAssist("init", { apiKey: "YOUR_API_KEY" }); // Don't initialize twice

2. Handle Errors Gracefully

Check if SiteAssist is loaded before calling:

if (window.SiteAssist) {
  SiteAssist("open");
} else {
  console.warn("SiteAssist not loaded yet");
}

3. Respect User Intent

Don't auto-open too aggressively:

// ✅ Good - give users time to browse
setTimeout(() => {
  if (!userHasInteracted) {
    SiteAssist("open");
  }
}, 30000); // 30 seconds

// ❌ Annoying - too soon
setTimeout(() => {
  SiteAssist("open");
}, 1000); // 1 second - too fast!

Error Handling

The SiteAssist API fails silently to avoid breaking your website. However, you can check the console for warnings:

// Check if API is available
if (typeof window.SiteAssist === "undefined") {
  console.warn("SiteAssist is not loaded");
}

// Wrap critical calls in try-catch if needed
try {
  SiteAssist("open");
} catch (error) {
  console.error("Failed to open widget:", error);
}

Next Steps

Need help with the API? Contact us at support@siteassist.io