API Reference
API Overview
Section titled “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
Section titled “Available Methods”Initializes the SiteAssist widget with your configuration.
Signature:
SiteAssist("init", options: InitOptions): voidParameters:
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.
Opens the chat widget.
Signature:
SiteAssist("open"): voidExample:
// Open the widget programmaticallySiteAssist("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);Closes the chat widget.
Signature:
SiteAssist("close"): voidExample:
// Close the widget programmaticallySiteAssist("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 awaywindow.addEventListener("beforeunload", () => { SiteAssist("close");});toggle
Section titled “toggle”Toggles the widget between open and closed states.
Signature:
SiteAssist("toggle"): voidExample:
// Toggle widget stateSiteAssist("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
Section titled “changeTheme”Changes the widget theme dynamically.
Signature:
SiteAssist("changeTheme", theme: "light" | "dark" | "auto"): voidParameters:
theme(string) - One of"light","dark", or"auto"
Example:
// Change to dark themeSiteAssist("changeTheme", "dark");
// Change to light themeSiteAssist("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 themefunction 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)
Section titled “track (Coming Soon)”Track custom events and analytics.
Signature:
SiteAssist("track", eventName: string, data?: any): voidStatus: 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 eventSiteAssist("track", "button_clicked");
// Track with additional dataSiteAssist("track", "product_viewed", { productId: "12345", productName: "Premium Widget", price: 99.99,});
// E-commerce trackingSiteAssist("track", "add_to_cart", { productId: "123", quantity: 1,});
SiteAssist("track", "purchase_completed", { orderId: "ORD-123", total: 199.99,});identify (Coming Soon)
Section titled “identify (Coming Soon)”Identify users with additional information.
Signature:
SiteAssist("identify", user: { externalId?: string; email?: string; name?: string; attributes?: Record<string, string>;}): voidStatus: 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
Section titled “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 readySiteAssist("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
Section titled “Custom Events”The widget dispatches custom events that you can listen to:
// Listen for custom widget eventswindow.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 eventswindow.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
Section titled “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 checkingwindow.SiteAssist("init", { apiKey: "pk_live_abc123", theme: "dark", // TypeScript will validate this});
// Open the widgetwindow.SiteAssist("open");
// Change themewindow.SiteAssist("changeTheme", "light");Complete API Example
Section titled “Complete API Example”Here’s a comprehensive example using multiple API methods:
// Initialize the widgetSiteAssist("init", { apiKey: "pk_live_abc123", type: "floating-bubble", theme: "auto",});
// Auto-open after 10 seconds for first-time visitorsif (!localStorage.getItem("siteassist_visited")) { setTimeout(() => { SiteAssist("open"); }, 10000);
localStorage.setItem("siteassist_visited", "true");}
// Sync theme with site theme switcherdocument.getElementById("site-theme-toggle").addEventListener("click", (e) => { const newTheme = e.target.dataset.theme; SiteAssist("changeTheme", newTheme);});
// Add custom help buttondocument.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
Section titled “Best Practices”1. Initialize Once
Section titled “1. Initialize Once”Only call init once per page load:
// ✅ GoodSiteAssist("init", { apiKey: "YOUR_API_KEY" });
// ❌ AvoidSiteAssist("init", { apiKey: "YOUR_API_KEY" });SiteAssist("init", { apiKey: "YOUR_API_KEY" }); // Don't initialize twice2. Handle Errors Gracefully
Section titled “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
Section titled “3. Respect User Intent”Don’t auto-open too aggressively:
// ✅ Good - give users time to browsesetTimeout(() => { if (!userHasInteracted) { SiteAssist("open"); }}, 30000); // 30 seconds
// ❌ Annoying - too soonsetTimeout(() => { SiteAssist("open");}, 1000); // 1 second - too fast!Error Handling
Section titled “Error Handling”The SiteAssist API fails silently to avoid breaking your website. However, you can check the console for warnings:
// Check if API is availableif (typeof window.SiteAssist === "undefined") { console.warn("SiteAssist is not loaded");}
// Wrap critical calls in try-catch if neededtry { SiteAssist("open");} catch (error) { console.error("Failed to open widget:", error);}Next Steps
Section titled “Next Steps”- Advanced Features - Explore text selection, fullscreen, and more
- Examples - See real-world implementation examples
- Configuration - Learn about all configuration options
Need help with the API? Contact us at support@siteassist.io