### Install Heyo.so SDK using Package Managers Source: https://heyo.so/docs/getting-started/installation Install the Heyo.so JavaScript SDK using npm, pnpm, yarn, or bun. This method is recommended for developers who need full TypeScript support and more control over the widget. ```bash npm install @heyo.so/js ``` ```bash pnpm add @heyo.so/js ``` ```bash yarn add @heyo.so/js ``` ```bash bun add @heyo.so/js ``` -------------------------------- ### Initialize Heyo.so SDK Source: https://heyo.so/docs/getting-started/installation Initialize the Heyo.so chat widget after installing the SDK. This can be done using either the default import or a namespace import style. The widget will automatically appear on your website after initialization. ```javascript import HEYO from '@heyo.so/js'; HEYO.init(); ``` -------------------------------- ### HEYO.identify() - Real-World Example (After Login) Source: https://heyo.so/docs/advanced-api-usage/identifying-users Example of how to call the identify() method after a user logs into your application, using their authenticated details. ```APIDOC ## HEYO.identify() - After User Login ### Description This example demonstrates how to call `HEYO.identify()` with user data obtained after a successful login event in your application. ### Method `HEYO.identify(userData)` ### Parameters #### Request Body - **userId** (string) - Required - The authenticated user's unique ID. - **email** (string) - Optional - The authenticated user's email address. - **name** (string) - Optional - The authenticated user's display name. ### Request Example ```javascript // Assuming 'auth' is your authentication object and 'user' contains login details auth.onLogin((user) => { HEYO.identify({ userId: user.id, email: user.email, name: user.displayName }); }); ``` ### Response This method updates the user identification state and sends data to the Heyo service. No direct response is returned to the caller. ``` -------------------------------- ### Install Heyo.so with HTML Script Tag Source: https://heyo.so/docs/getting-started/installation This method is the easiest way to add the Heyo.so chat widget to your website. Simply include the provided script tag before the closing `` tag in your HTML file. No additional dependencies are required. ```html ``` -------------------------------- ### Preview Heyo.so on Localhost with Project ID Source: https://heyo.so/docs/getting-started/installation To preview the Heyo.so widget during local development, you need to provide your Project ID. This can be done by adding the `data-project-id` attribute to the script tag or passing it to the `init` function of the SDK. Your Project ID can be found in the dashboard Project Settings. ```html ``` ```javascript HEYO.init({ projectId: 'YOUR_PROJECT_ID' }); ``` -------------------------------- ### Best Practices: Naming Conventions (HEYO SDK) Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields This example demonstrates clear and descriptive naming conventions for tags and custom fields using the HEYO SDK. It shows preferred usage like 'trial-user' and 'subscription-plan', contrasting with abbreviations that reduce clarity. ```javascript // ✅ Good HEYO.addTag('trial-user'); HEYO.setField('subscription-plan', 'pro'); // ❌ Avoid abbreviations HEYO.addTag('trl'); HEYO.setField('sub-pln', 'pro'); ``` -------------------------------- ### Real-World Example: SaaS Application Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields Tracks subscription and usage details for SaaS applications by setting custom fields and tags related to the user's plan, payment status, and trial information. ```javascript // User subscription info HEYO.setField('plan', user.subscription.plan); // "starter", "pro", "enterprise" HEYO.setField('mrr', user.subscription.mrr); HEYO.setField('trial-ends', user.subscription.trialEndsAt); HEYO.setField('is-paying', user.subscription.isActive); // Tags for quick filtering HEYO.addTag(user.subscription.plan); // "starter", "pro", etc. if (user.subscription.isActive) HEYO.addTag('paying-customer'); if (user.subscription.isTrial) HEYO.addTag('trial-user'); ``` -------------------------------- ### Real-World Example: E-Commerce Store Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields Tracks customer value and status by identifying the user and setting relevant tags and custom fields. This snippet illustrates a common use case for e-commerce businesses. ```javascript // After user logs in HEYO.identify({ userId: user.id, email: user.email, name: user.name, }); // Add relevant tags HEYO.addTag('customer'); if (user.orders.length > 0) HEYO.addTag('has-purchased'); if (user.totalSpent > 1000) HEYO.addTag('high-value'); // Set custom fields HEYO.setField('total-spent', user.totalSpent); HEYO.setField('order-count', user.orders.length); HEYO.setField('last-purchase', user.lastOrderDate); HEYO.setField('is-vip', user.isVIP); ``` -------------------------------- ### Best Practices: Keep It Simple (HEYO SDK) Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields This code illustrates the principle of keeping tag and field usage simple with the HEYO SDK. It shows the 'good' example of using essential information like 'paying-customer', 'plan', and 'mrr', while highlighting the 'too much' example of excessive, redundant tagging. ```javascript // ✅ Good - essential info HEYO.addTag('paying-customer'); HEYO.setField('plan', 'pro'); HEYO.setField('mrr', 99); // ❌ Too much - overwhelming HEYO.addTag('customer'); HEYO.addTag('paying'); HEYO.addTag('active'); HEYO.addTag('verified'); HEYO.addTag('engaged'); // ... 20 more tags ``` -------------------------------- ### Add Heyo Script Tag to Website Source: https://heyo.so/docs/getting-started/introduction Integrates the Heyo live-chat widget into your website by adding a script tag before the closing tag. This is the simplest way to get started. ```html ``` -------------------------------- ### Best Practices: Using Tags for Categories (HEYO SDK) Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields This example illustrates the best practice of using tags for simple categorization with the HEYO SDK. It shows adding tags like 'premium', 'active', and 'verified' for clear segmentation, contrasting it with avoiding complex state information in tags. ```javascript // ✅ Good - simple categories HEYO.addTag('premium'); HEYO.addTag('active'); HEYO.addTag('verified'); // ❌ Avoid - complex state better in fields HEYO.addTag('plan-premium-monthly-299'); // Use custom field instead ``` -------------------------------- ### Get Current Agent Status and React Source: https://heyo.so/docs/advanced-api-usage/agent-status-and-events Retrieves the current agent status and uses a switch statement to perform different actions based on whether the agent is 'online', 'away', or 'offline'. This is useful for tailoring user experiences based on real-time availability. ```javascript const status = HEYO.getAgentStatus(); switch (status) { case 'online': console.log('Agent is available to chat'); break; case 'away': console.log('Agent is away but may return soon'); break; case 'offline': console.log('Agent is offline'); break; } ``` -------------------------------- ### Show Heyo Widget After User Scrolls with JavaScript Source: https://heyo.so/docs/getting-started/basic-api-usage Trigger the Heyo chat widget to appear after a user scrolls a certain distance down the page. This example adds a scroll event listener that calls `HEYO.show()` when the vertical scroll position exceeds 500 pixels. ```javascript window.addEventListener('scroll', () => { if (window.scrollY > 500) { HEYO.show(); } }); ``` -------------------------------- ### Conditional Heyo Widget Styling Per Page Source: https://heyo.so/docs/advanced-api-usage/customizing-appearance Dynamically change the Heyo widget's appearance based on the current page URL. This allows for different styles on the landing page versus the dashboard, for example. ```javascript // Landing page - prominent agent card if (window.location.pathname === '/') { HEYO.configure({ widgetStyle: 'agent-card', widgetSize: 'large', widgetPosition: 'right', }); } // Dashboard - minimal bubble if (window.location.pathname.includes('/dashboard')) { HEYO.configure({ widgetStyle: 'bubble', widgetSize: 'small', widgetPosition: 'left', }); } ``` -------------------------------- ### Track Onboarding Progress with HEYO SDK Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields This snippet demonstrates how to track user progress through an onboarding flow using the HEYO SDK. It involves setting fields for onboarding state and completion, and managing tags to indicate progress status. ```javascript // Onboarding state HEYO.setField('onboarding-step', 'profile-setup'); HEYO.setField('onboarding-started', '2025-01-15'); HEYO.setField('completed-steps', 3); // Tags for each milestone HEYO.addTag('onboarding-in-progress'); // When user completes onboarding HEYO.removeTag('onboarding-in-progress'); HEYO.addTag('onboarding-complete'); HEYO.setField('onboarding-step', 'complete'); HEYO.setField('onboarding-completed', '2025-01-20'); ``` -------------------------------- ### Initialize Heyo Widget with JS SDK Options Source: https://heyo.so/docs/advanced-api-usage/initialization-options Initialize the Heyo widget using the JS SDK and pass various configuration options. Supported options include projectId, hidden, and logs. This method is suitable for dynamic configuration within your JavaScript application. ```javascript import { HEYO } from '@heyo.so/js'; // or: import HEYO from '@heyo.so/js' HEYO.init({ projectId: 'YOUR_PROJECT_ID', hidden: true, }); ``` ```javascript HEYO.init({ projectId: '665b12a3b4c5d6e7f8g9h0i1', }); ``` ```javascript HEYO.init({ projectId: 'YOUR_PROJECT_ID', hidden: true, }); // Show it later when needed setTimeout(() => { HEYO.show(); }, 5000); ``` ```javascript HEYO.init({ projectId: 'YOUR_PROJECT_ID', logs: 'debug', // Options: 'debug', 'minimal', 'none' }); ``` ```javascript // Initialize but keep hidden HEYO.init({ projectId: 'YOUR_PROJECT_ID', hidden: true, }); // Check authentication if (user.isAuthenticated) { HEYO.show(); HEYO.identify({ userId: user.id, email: user.email, name: user.name, }); } ``` ```javascript const isDevelopment = window.location.hostname === 'localhost'; HEYO.init({ projectId: isDevelopment ? 'YOUR_PROJECT_ID' : undefined, hidden: isDevelopment, // Hide in development }); ``` -------------------------------- ### Initialize Heyo Widget with HTML Script Attributes Source: https://heyo.so/docs/advanced-api-usage/initialization-options Configure the Heyo widget by setting options as data attributes directly on the HTML script tag. This method is useful for static configuration or when not using a JS SDK. Options like projectId, hidden, and logs can be specified. ```html ``` -------------------------------- ### Best Practices: Using Custom Fields for Data (HEYO SDK) Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields This snippet highlights the recommended approach of using custom fields for specific data points with the HEYO SDK. It shows setting structured data like 'plan', 'billing-cycle', and 'price', and advises against using fields for simple boolean states better represented by tags. ```javascript // ✅ Good - structured data HEYO.setField('plan', 'premium'); HEYO.setField('billing-cycle', 'monthly'); HEYO.setField('price', 299); // ❌ Avoid - boolean states better as tags HEYO.setField('is-premium', true); // Use tag instead ``` -------------------------------- ### Qualify Leads with HEYO SDK Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields This code illustrates how to qualify leads using the HEYO SDK by tracking user engagement metrics and adding specific tags based on user actions. It sets fields for page views and time on site, and adds tags like 'qualified-lead', 'hot-lead', and 'enterprise-prospect'. ```javascript // Track engagement HEYO.setField('page-views', sessionStorage.pageViewCount); HEYO.setField('time-on-site', calculateTimeOnSite()); HEYO.setField('last-visit', new Date().toISOString()); // Qualify leads if (user.downloadedWhitepaper) HEYO.addTag('qualified-lead'); if (user.requestedDemo) HEYO.addTag('hot-lead'); if (user.company.size > 50) HEYO.addTag('enterprise-prospect'); ``` -------------------------------- ### Set All Tags for Visitors Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields Replaces all existing tags on a visitor's profile with a new set of tags. This is useful for comprehensively updating a visitor's categorization. ```javascript HEYO.setTags(['premium', 'active', 'verified']); ``` -------------------------------- ### Execute code when Heyo widget is ready Source: https://heyo.so/docs/advanced-api-usage/widget-events The onReady() callback executes code once the Heyo widget is fully loaded and initialized. If the widget is already ready when onReady() is called, the callback runs immediately; otherwise, it's queued. This is useful for actions that depend on the widget's initialization. ```javascript HEYO.onReady(() => { console.log('Widget is ready!'); }); ``` ```javascript HEYO.onReady(() => { console.log('Heyo widget loaded successfully'); analytics.track('chat_widget_loaded'); }); ``` ```javascript async function initializeChat() { const user = await fetchCurrentUser(); HEYO.onReady(() => { if (user) { HEYO.identify({ userId: user.id, email: user.email, name: user.name, }); } }); } initializeChat(); ``` ```javascript HEYO.onReady(() => { Sentry.addBreadcrumb({ category: 'chat', message: 'Chat widget initialized', level: 'info', }); }); ``` -------------------------------- ### Directly call widget methods without onReady Source: https://heyo.so/docs/advanced-api-usage/widget-events For most widget methods like identify(), open(), and configure(), explicit use of onReady() is unnecessary. The Heyo SDK automatically queues these calls until the widget is ready, allowing them to be invoked directly after script loading. ```javascript // ✅ Just call them directly - they're automatically queued HEYO.identify({ userId: '123' }); HEYO.open(); HEYO.configure({ widgetColor: '#10b981' }); ``` -------------------------------- ### HEYO.identify() - Basic Identification Source: https://heyo.so/docs/advanced-api-usage/identifying-users Identify users by providing their unique ID, email, and name. This helps in linking conversations and providing context to your support team. ```APIDOC ## HEYO.identify() ### Description Identifies a user and links their conversations to their profile. This allows support teams to see user information and conversation history. ### Method `HEYO.identify(userData)` ### Parameters #### Request Body - **userId** (string) - Required - Your internal unique identifier for the user. - **email** (string) - Optional - The user's email address. - **name** (string) - Optional - The user's display name. ### Request Example ```javascript HEYO.identify({ userId: '12345', email: 'john@example.com', name: 'John Doe' }); ``` ### Response This method does not return a response. It updates the user identification state on the client-side and sends data to the Heyo service. ### Error Handling - If `userId` is missing, the identification may fail or not be processed correctly. - Invalid data types for email or name might be ignored or cause unexpected behavior. ``` -------------------------------- ### Set Custom Fields for Smart Value Display Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields Shows how setting custom fields with specific formats like URLs, emails, dates, booleans, and large numbers results in smart, formatted display in the dashboard. ```javascript // URLs: HEYO.setField('website', 'https://example.com'); // Emails: HEYO.setField('support-email', 'help@acme.com'); // Dates: HEYO.setField('trial-ends', '2025-02-15'); HEYO.setField('signup-date', '2025-01-15T10:30:00Z'); // Booleans: HEYO.setField('is-premium', true); HEYO.setField('trial-expired', false); // Large Numbers: HEYO.setField('total-revenue', 125000); ``` -------------------------------- ### Set Custom Fields with Supported Value Types Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields Demonstrates setting custom fields using different supported data types: strings, numbers, and booleans. This ensures data integrity and proper display. ```javascript // Strings: HEYO.setField('plan', 'premium'); HEYO.setField('subscription-id', 'sub_1A2B3C'); // Numbers: HEYO.setField('account-balance', 1500); HEYO.setField('total-purchases', 42); // Booleans: HEYO.setField('is-verified', true); HEYO.setField('newsletter-subscribed', false); ``` -------------------------------- ### Set Custom Fields for Visitors Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields Adds or updates custom key-value data for a visitor. Supports string, number, and boolean types. Field keys are normalized to kebab-case and values are displayed with smart formatting in the dashboard. ```javascript HEYO.setField('plan', 'premium'); HEYO.setField('signup-date', '2025-01-15'); HEYO.setField('is-subscribed', true); HEYO.setField('monthly-revenue', 299); ``` -------------------------------- ### Prompt Users Before Opening Offline Chat (JavaScript) Source: https://heyo.so/docs/advanced-api-usage/agent-status-and-events Attaches an event listener to a chat button. When clicked, it checks agent status. If offline, it prompts the user to confirm if they want to leave a message before forcing the chat open. If online, it opens the chat directly. ```javascript const chatButton = document.getElementById('chat-button'); chatButton.onclick = () => { const status = HEYO.getAgentStatus(); if (status === 'offline') { const confirmed = confirm( 'Our agents are currently offline. Would you like to leave a message?' ); if (confirmed) { HEYO.open({ force: true }); } } else { HEYO.open(); } }; ``` -------------------------------- ### Add Tags to Visitors Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields Adds one or more tags to a visitor's profile for categorization. Tags are automatically normalized to kebab-case. This function is useful for segmenting users based on their status or attributes. ```javascript HEYO.addTag('vip'); HEYO.addTag('paid-user'); HEYO.addTag('onboarding-complete'); ``` -------------------------------- ### Show and Hide Entire Widget with JavaScript Source: https://heyo.so/docs/getting-started/basic-api-usage Control the overall visibility of the Heyo chat widget on the page. The `show()` and `hide()` functions are part of the global `HEYO` object. `HEYO.show({ force: true })` can be used to display the widget even when agents are offline. ```javascript HEYO.hide(); // Hide the widget completely HEYO.show(); // Show the widget HEYO.show({ force: true }); // Show even when agents are offline ``` -------------------------------- ### Identify User with Heyo SDK (JavaScript) Source: https://heyo.so/docs/advanced-api-usage/identifying-users Identifies a user by providing their email, name, and a unique userId. This allows Heyo to link conversations and user information to your dashboard for personalized support. ```javascript HEYO.identify({ email: 'john@example.com', name: 'John Doe', userId: '12345', }); ``` ```javascript HEYO.identify({ email: 'sarah@company.com', name: 'Sarah Wilson', userId: 'user_789', }); ``` ```javascript // When your authentication completes auth.onLogin((user) => { HEYO.identify({ email: user.email, name: user.displayName, userId: user.id, }); }); ``` -------------------------------- ### Check Chat Status with JavaScript Source: https://heyo.so/docs/getting-started/basic-api-usage Determine if the Heyo chat window is currently open. The `isOpen()` function returns a boolean value, which can be used in conditional logic. This is useful for logging or triggering other actions based on the chat's state. ```javascript const isChatOpen = HEYO.isOpen(); if (isChatOpen) console.log('Chat is open'); else console.log('Chat is closed'); ``` -------------------------------- ### Agent Status API Source: https://heyo.so/docs/advanced-api-usage/agent-status-and-events This section covers methods for retrieving the current agent status and subscribing to status change events. ```APIDOC ## Agent Status API ### Description Monitor agent availability and respond to status changes in real-time. Heyo provides methods to check agent status and listen for status changes, helping you create more dynamic experiences based on agent availability. Agents can have three statuses: `online`, `away`, `offline`. ### Methods #### `getAgentStatus()` ##### Description Retrieves the current status of the agents. ##### Method `HEYO.getAgentStatus()` ##### Returns - `string`: The current agent status ('online', 'away', or 'offline'). ##### Example ```javascript const status = HEYO.getAgentStatus(); switch (status) { case 'online': console.log('Agent is available to chat'); break; case 'away': console.log('Agent is away but may return soon'); break; case 'offline': console.log('Agent is offline'); break; } ``` #### `onAgentStatusChange(callback)` ##### Description Registers a callback function to be executed whenever the agent status changes. ##### Method `HEYO.onAgentStatusChange(callback)` ##### Parameters - **callback** (function) - Required - A function that will be called with the new status as an argument. ##### Example ```javascript HEYO.onAgentStatusChange((status) => { console.log('Agent is now:', status); }); ``` ``` -------------------------------- ### Force Show/Open Widget When Offline Source: https://heyo.so/docs/advanced-api-usage/agent-status-and-events Overrides the 'hide when offline' behavior to force the widget to show or open even when all agents are offline. This is useful for allowing users to leave messages when no agents are immediately available. ```javascript // Show the widget even if hideWhenOffline is enabled and all agents are offline HEYO.show({ force: true }); // Open the chat even if hideWhenOffline is enabled and all agents are offline HEYO.open({ force: true }); ``` -------------------------------- ### Check Status Before Opening Chat (JavaScript) Source: https://heyo.so/docs/advanced-api-usage/agent-status-and-events Checks the current agent status before attempting to open the chat. If agents are offline, it alerts the user and then forces the chat open to allow message submission. Otherwise, it opens the chat normally. ```javascript const status = HEYO.getAgentStatus(); if (status === 'online') { HEYO.open(); } else { alert('Our support team is currently offline. Please leave a message!'); HEYO.open({ force: true }); // Open anyway to leave a message } ``` -------------------------------- ### Listen for Agent Status Changes Source: https://heyo.so/docs/advanced-api-usage/agent-status-and-events Subscribes to real-time updates for agent status changes using the `onAgentStatusChange` callback. This function is executed whenever an agent's status transitions, allowing your application to react dynamically. ```javascript HEYO.onAgentStatusChange((status) => { console.log('Agent is now:', status); }); ``` -------------------------------- ### Control Heyo Chat from HTML Button Source: https://heyo.so/docs/getting-started/basic-api-usage Integrate Heyo chat functionality directly into HTML elements, such as a button. The `onclick` event handler can call `HEYO.open()` to launch the chat window when the button is clicked. ```html ``` -------------------------------- ### Open, Close, and Toggle Chat Window with JavaScript Source: https://heyo.so/docs/getting-started/basic-api-usage Control the expanded or collapsed state of the Heyo chat window. These functions are available on the global `HEYO` object and work with both the HTML script tag and the JS SDK. An optional parameter `{ force: true }` can override the 'Hide when offline' setting. ```javascript HEYO.open(); // Open the chat window HEYO.close(); // Close the chat window HEYO.toggle(); // Toggle between open and closed // Override the "hide when offline" setting and show the widget anyway HEYO.open({ force: true }); ``` -------------------------------- ### HEYO.logout() - Manual Logout Source: https://heyo.so/docs/advanced-api-usage/identifying-users Explicitly clear the current user session using the logout() method, typically called when a user logs out of your application. ```APIDOC ## HEYO.logout() ### Description Clears the current user session, resets the widget state, and logs the user out from Heyo tracking. This is useful when a user explicitly logs out of your application. ### Method `HEYO.logout()` ### Parameters This method does not accept any parameters. ### Request Example ```javascript HEYO.logout(); ``` ### Response This method does not return a response. It clears session cookies and resets the widget state locally. ``` -------------------------------- ### Widget Visibility Control Source: https://heyo.so/docs/advanced-api-usage/agent-status-and-events Control the visibility of the Heyo widget based on agent online status and override default behavior. ```APIDOC ## Widget Visibility Control ### Description Manage the Heyo widget's visibility, particularly when agents are offline. By default, the widget can be configured to hide when all agents are offline. You can also force the widget to show or open even when agents are offline. ### Hide Widget When Offline #### Description When enabled in Project Settings, the widget automatically hides if all agents go offline. It reappears when agents come online only if the user has shown interest (e.g., by calling `HEYO.open()` or `HEYO.show()`). #### How it works: - Page loads with all agents offline → widget stays hidden. - Page loads with agents online → widget shows normally. - Widget was visible, agents go offline → widget hides. - Widget was visible before going offline, agents come back online → widget re-appears. - Widget was never shown, agents come online → widget stays hidden (respects user preference). ### Force Showing/Opening When Offline #### Description Override the "hide when offline" behavior to ensure the widget is visible or open even if no agents are available. #### Methods ##### `show({ force: true })` - **Description**: Forces the widget to show, even if the 'Hide when offline' setting is enabled and all agents are offline. - **Example**: `HEYO.show({ force: true });` ##### `open({ force: true })` - **Description**: Forces the chat to open, even if the 'Hide when offline' setting is enabled and all agents are offline. - **Example**: `HEYO.open({ force: true });` #### Use Case Useful when you want to provide users the option to leave a message even when no agents are available. ``` -------------------------------- ### Execute code when agent status changes Source: https://heyo.so/docs/advanced-api-usage/widget-events The onAgentStatusChange() callback executes code when the agent's status transitions. It's called immediately with the current status upon registration and subsequently whenever the status changes. The callback receives one of three status values: 'online', 'away', or 'offline'. ```javascript HEYO.onAgentStatusChange((status) => { console.log('Agent status changed to:', status); if (status === 'online') { showNotification('Support is now available!'); } }); ``` ```javascript const statusIndicator = document.getElementById('support-status'); HEYO.onAgentStatusChange((status) => { if (status === 'online') { statusIndicator.textContent = '🟢 Chat available'; statusIndicator.style.color = '#22c55e'; } else if (status === 'away') { statusIndicator.textContent = '🟡 Be right back'; statusIndicator.style.color = '#f59e0b'; } else { statusIndicator.textContent = '⚫ Leave a message'; statusIndicator.style.color = '#6b7280'; } }); ``` ```javascript let hasPrompted = false; HEYO.onAgentStatusChange((status) => { if (status === 'online' && !hasPrompted) { hasPrompted = true; setTimeout(() => HEYO.open(), 3000); } }); ``` ```javascript HEYO.onAgentStatusChange((status) => { updateSupportButton(status); }); HEYO.onAgentStatusChange((status) => { analytics.track('agent_status_changed', { status }); }); ``` -------------------------------- ### A/B Test Heyo Widget Styles Source: https://heyo.so/docs/advanced-api-usage/customizing-appearance Implement A/B testing for different Heyo widget styles by randomly configuring the widget style based on a probability. ```javascript // Random A/B test const showAgentCard = Math.random() > 0.5; HEYO.configure({ widgetStyle: showAgentCard ? 'agent-card' : 'bubble', }); ``` -------------------------------- ### Log Out User with Heyo SDK (JavaScript) Source: https://heyo.so/docs/advanced-api-usage/identifying-users Manually logs out the current user by clearing session cookies and resetting the widget state. This is useful when a user explicitly logs out of your application. ```javascript HEYO.logout(); ``` -------------------------------- ### Set Heyo Widget Color Source: https://heyo.so/docs/advanced-api-usage/customizing-appearance Match your brand colors by setting the widget color. Accepts hex codes, RGB values, or standard color names. ```javascript HEYO.configure({ widgetColor: '#ef4444' }); ``` -------------------------------- ### Configure Heyo Widget Appearance Source: https://heyo.so/docs/advanced-api-usage/customizing-appearance Set the default appearance of the Heyo widget including color, style, position, and size. This configuration is applied globally unless overridden by specific instance configurations. ```javascript HEYO.configure({ widgetColor: '#10b981', widgetStyle: 'bubble', widgetPosition: 'right', widgetSize: 'medium', }); ``` -------------------------------- ### Remove Tags from Visitors Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields Removes a specific tag from a visitor's profile. This is useful when a visitor's status or attribute changes and the old tag is no longer relevant. ```javascript HEYO.removeTag('trial-user'); ``` -------------------------------- ### POST /api/conversations/{conversationId}/tags Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields This endpoint allows for adding, removing, or setting tags for a specific conversation. It is typically used after events like payment webhooks to update a user's tag status. ```APIDOC ## POST /api/conversations/{conversationId}/tags ### Description Updates tags associated with a specific conversation. Supports adding, removing, or setting tags. ### Method POST ### Endpoint `/api/conversations/{conversationId}/tags` ### Parameters #### Path Parameters - **conversationId** (string) - Required - The unique identifier for the conversation. #### Query Parameters None #### Request Body - **operation** (string) - Required - The operation to perform. Accepts `add`, `remove`, or `set`. - **tags** (string | string[]) - Required - A single tag or an array of tags to be updated. ### Request Example ```json { "operation": "add", "tags": ["paid-user", "premium"] } ``` ### Response #### Success Response (200) Typically returns an empty response or a confirmation message upon successful update. #### Response Example ```json { "message": "Tags updated successfully." } ``` ``` -------------------------------- ### POST /api/conversations/{conversationId}/fields Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields This endpoint allows for setting or removing custom fields for a specific conversation. It is useful for updating structured user data, such as subscription details, after relevant backend events. ```APIDOC ## POST /api/conversations/{conversationId}/fields ### Description Updates custom fields associated with a specific conversation. Supports setting or removing field values. ### Method POST ### Endpoint `/api/conversations/{conversationId}/fields` ### Parameters #### Path Parameters - **conversationId** (string) - Required - The unique identifier for the conversation. #### Query Parameters None #### Request Body - **operation** (string) - Required - The operation to perform. Accepts `set` or `remove`. - **key** (string) - Required - The key of the custom field to update. - **value** (string | number | boolean) - Required for `set` operation - The value to set for the custom field. ### Request Example ```json { "operation": "set", "key": "subscription-id", "value": "sub_1A2B3C4D" } ``` ### Response #### Success Response (200) Typically returns an empty response or a confirmation message upon successful update. #### Response Example ```json { "message": "Field updated successfully." } ``` ``` -------------------------------- ### Set Heyo Widget Position Source: https://heyo.so/docs/advanced-api-usage/customizing-appearance Determine the placement of the Heyo widget on the screen. Options are 'left' for the bottom-left corner or 'right' for the bottom-right corner. ```javascript HEYO.configure({ widgetPosition: 'right' }); ``` -------------------------------- ### Remove Custom Fields from Visitors Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields Removes a specific custom field and its associated value from a visitor's profile. This is useful for cleaning up data or removing temporary information. ```javascript HEYO.removeField('temp-data'); ``` -------------------------------- ### Set Heyo Widget Size Source: https://heyo.so/docs/advanced-api-usage/customizing-appearance Adjust the size of the Heyo widget. Available options are 'small', 'medium' (default), and 'large' (only for 'bubble' style). ```javascript HEYO.configure({ widgetSize: 'small' }); ``` -------------------------------- ### Set Heyo Widget Style Source: https://heyo.so/docs/advanced-api-usage/customizing-appearance Customize the visual style of the Heyo widget. Options include 'bubble' for a simple floating button or 'agent-card' to display agent information with an avatar and status. ```javascript HEYO.configure({ widgetStyle: 'bubble' }); ``` -------------------------------- ### Update Tags via Server-Side API Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields This snippet shows how to update tags for a conversation from a backend server using the Heyo REST API. It sends a POST request to the conversations tags endpoint with the desired operation (add, remove, or set) and the tags to modify. ```javascript // After payment webhook await fetch(`/api/conversations/${conversationId}/tags`, { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: JSON.stringify({ operation: 'add', tags: ['paid-user', 'premium'], }), }); ``` -------------------------------- ### Update Custom Fields via Server-Side API Source: https://heyo.so/docs/advanced-api-usage/tags-and-custom-fields This code demonstrates how to update custom fields for a conversation using the Heyo REST API from a backend service. It uses a POST request to the conversations fields endpoint, specifying the operation ('set' or 'remove'), the key, and the value. ```javascript // After subscription change await fetch(`/api/conversations/${conversationId}/fields`, { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: JSON.stringify({ operation: 'set', key: 'subscription-id', value: 'sub_1A2B3C4D', }), }); ``` -------------------------------- ### Conditionally Hide Heyo Widget on Specific Pages with JavaScript Source: https://heyo.so/docs/getting-started/basic-api-usage Prevent the Heyo chat widget from displaying on certain pages by checking the current URL path. This JavaScript code snippet checks the `window.location.pathname` and calls `HEYO.hide()` if it matches a specific route, like '/checkout'. ```javascript const pathName = window.location.pathname; if (pathName === '/checkout') HEYO.hide(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.