> For the complete documentation index, see [llms.txt](https://docs.wonderchat.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.wonderchat.io/api-reference/client-sdk.md).

# Client SDK

Client-side SDK functions for controlling the Wonderchat widget

The Wonderchat Client SDK provides JavaScript functions that allow you to programmatically control the chat widget on your website. These functions are available through the `wonderchat` object on the `window` object after the Wonderchat widget script is loaded.

## Prerequisites

Before using these SDK functions, ensure that the Wonderchat widget script is properly embedded on your website. The functions will only be available after the widget has fully loaded.

## Available Functions

### wonderchat.changeChatbotId()

Changes the current chatbot displayed in the widget. This is useful when you want to dynamically switch between different chatbots based on user actions or page context.

**Syntax:**

```javascript
wonderchat.changeChatbotId(chatbotId);
```

**Parameters:**

* `chatbotId` (string, required): The ID of the chatbot you want to switch to

**Example:**

```javascript
// Switch to a different chatbot
wonderchat.changeChatbotId("your-new-chatbot-id");

// Example: Switch chatbot based on user selection
function switchToSupportBot() {
  wonderchat.changeChatbotId("support-bot-123");
}

function switchToSalesBot() {
  wonderchat.changeChatbotId("sales-bot-456");
}
```

### wonderchat.toggleChat()

Controls the open/closed state of the chat widget. Can be used to programmatically open or close the chat, or toggle between states.

**Syntax:**

```javascript
wonderchat.toggleChat(show);
```

**Parameters:**

* `show` (boolean, optional):
  * `true`: Opens the chat widget
  * `false`: Closes the chat widget
  * If omitted: Toggles the current state

**Examples:**

```javascript
// Toggle the chat widget state
wonderchat.toggleChat();

// Explicitly open the chat widget
wonderchat.toggleChat(true);

// Explicitly close the chat widget
wonderchat.toggleChat(false);

// Example: Open chat when user clicks a help button
document.getElementById("help-button").addEventListener("click", () => {
  wonderchat.toggleChat(true);
});
```

### wonderchat.chatbotIdentify()

Identifies the user for the current chat session. This helps in tracking conversations and providing personalized support.

`window.wonderchat` exposes this method as `wonderchat.chatbotIdentify(...)`. It is also available as the global `window.chatbotIdentify(...)`.

**Syntax:**

```javascript
wonderchat.chatbotIdentify(params);
```

**Parameters:**

* `params` (object, required): An object containing user identification data
  * `email` (string, optional): The user's email address
  * `name` (string, optional): The user's name
  * `phoneNumber` (string, optional): The user's phone number
  * `token` (string, optional): An identity verification token (JWT). See [Identity Verification](/setup-guides/adding-your-chatbot-to-your-website/identity-verification.md)
  * `custom` (object, optional): An object containing any arbitrary custom identifiers

**Canonical usage:**

```javascript
window.chatbotLoaded(() => {
  wonderchat.chatbotIdentify({
    custom: { pageUrl: window.location.href }
  });
});
```

**Examples:**

```javascript
// Identify a user by email
wonderchat.chatbotIdentify({ email: "user@example.com" });

// Identify a user with multiple fields
wonderchat.chatbotIdentify({
  email: "user@example.com",
  name: "John Doe",
  phoneNumber: "+1234567890"
});

// Identify a user with custom fields
wonderchat.chatbotIdentify({
  email: "user@example.com",
  name: "John Doe",
  custom: {
    userId: "12345",
    accountType: "premium",
    company: "Acme Corp",
    department: "Engineering"
  }
});

// Example: Identify user after login
function onUserLogin(userData) {
  // Your login logic here

  // Identify the user in Wonderchat
  wonderchat.chatbotIdentify({
    email: userData.email,
    name: userData.name,
    phoneNumber: userData.phone,
    custom: {
      userId: userData.id,
      accountType: userData.subscription
    }
  });
}

// Example: Identify user from a form submission
document.getElementById("contact-form").addEventListener("submit", (e) => {
  e.preventDefault();
  const formData = new FormData(e.target);
  
  wonderchat.chatbotIdentify({
    email: formData.get("email"),
    name: formData.get("name"),
    phoneNumber: formData.get("phone"),
    custom: {
      source: "contact-form",
      interests: formData.get("interests")
    }
  });
});
```

#### Using custom values in Custom Tools

Values sent in the `custom` object are stored on the conversation under `customIdentifiers`. You can pass one of these values directly into a [Custom Tool's](/setup-guides/using-chatbot-tools/set-up-custom-chatbot-tools.md) API call:

1. Edit the tool's **Input Parameter**.
2. Set **Value Source** → **Custom identifier**.
3. Enter the exact key name you sent in `custom` (e.g. `pageUrl`).

The value is filled in server-side at call time and is never shown to the AI, so it can't be guessed or altered. The key name is **case-sensitive** and must match the `custom` key exactly.

**Timing:** Call `chatbotIdentify` before the message that triggers the tool. The `chatbotLoaded` callback (as in the canonical example above) is the right place. If the very first message is sent before the identify call completes, that first turn may not have the value yet.

**Update semantics:** `custom` keys are merged per call, and the latest value for a key wins.

* For "the current page," send `pageUrl` on every navigation.
* For "the page where the chat was opened," send it once at load under a distinct key (e.g. `landingPageUrl`) and don't resend it.

**Limits and caveats:**

* Each custom string value is capped at **5000 characters** — longer values are truncated.
* Values are supplied by the site and are **not verified**. This is safe for things like a page URL, but they must not be treated as an authenticated identity or used as a sole key for sensitive lookups. For verified identity, use [Identity Verification](/setup-guides/adding-your-chatbot-to-your-website/identity-verification.md).

### wonderchat.clearChatbotHistory()

Clears the current chat history and starts a new chat session. This function removes all previous messages from the conversation and initializes a fresh chat session with the chatbot.

**Syntax:**

```javascript
wonderchat.clearChatbotHistory();
```

**Parameters:**

* None

**Examples:**

```javascript
// Clear chat history and start a new session
wonderchat.clearChatbotHistory();

// Example: Clear history when user clicks a "New Chat" button
document.getElementById("new-chat-button").addEventListener("click", () => {
  wonderchat.clearChatbotHistory();
});

// Example: Clear history after completing a transaction
function onTransactionComplete() {
  // Your transaction logic here

  // Start a fresh chat session
  wonderchat.clearChatbotHistory();
  wonderchat.toggleChat(true); // Optionally open the chat
}
```

### wonderchat.prefillChatbotQuestion()

Programmatically prefills a question in the chatbot's input field for the user to send. This allows you to guide users by suggesting relevant questions based on the page context or user actions.

**Syntax:**

```javascript
wonderchat.prefillChatbotQuestion(question);
```

**Parameters:**

* `question` (string, required): The text to prefill in the chatbot's input field

**Examples:**

```javascript
// Prefill a question
wonderchat.prefillChatbotQuestion("How do I reset my password?");

// Example: Prefill question based on clicked FAQ item
document.querySelectorAll(".faq-item").forEach((item) => {
  item.addEventListener("click", () => {
    const question = item.getAttribute("data-question");
    wonderchat.prefillChatbotQuestion(question);
    wonderchat.toggleChat(true); // Open chat with prefilled question
  });
});

// Example: Prefill question from a help menu
function showHelpForFeature(feature) {
  const questions = {
    billing: "How can I update my billing information?",
    api: "How do I get started with the API?",
    integrations: "What integrations are available?",
  };

  if (questions[feature]) {
    wonderchat.prefillChatbotQuestion(questions[feature]);
    wonderchat.toggleChat(true);
  }
}

// Example: Prefill question from URL parameter
const urlParams = new URLSearchParams(window.location.search);
const question = urlParams.get("question");
if (question) {
  window.chatbotLoaded(() => {
    wonderchat.prefillChatbotQuestion(decodeURIComponent(question));
    wonderchat.toggleChat(true);
  });
}
```

**Note:** The prefilled question appears in the input field but is not automatically sent. Users need to click send or press Enter to submit the question.

## Best Practices

1. **Wait for Widget Load**: Ensure the Wonderchat widget script is loaded and ready before calling SDK functions. The script must be embedded on your page first, then use the `chatbotLoaded` callback:

   ```javascript
   // Use the chatbotLoaded callback to ensure the widget is ready
   window.chatbotLoaded(() => {
     // SDK functions are now available through the wonderchat object
     wonderchat.chatbotIdentify({ email: "user@example.com" });
     wonderchat.toggleChat(false); // Start with chat closed
   });
   ```

**Important**: The Wonderchat widget script must be loaded on your page before you can use `window.chatbotLoaded()` or any SDK functions.

2. **Error Handling**: Wrap SDK calls in try-catch blocks to handle cases where the widget might not be loaded:

   ```javascript
   try {
     wonderchat.changeChatbotId("new-bot-id");
   } catch (error) {
     console.error("Wonderchat widget not loaded:", error);
   }
   ```
3. **User Experience**: Consider the user experience when programmatically controlling the chat:
   * Don't open the chat automatically on page load unless necessary
   * Provide clear UI elements for users to control the chat state
   * Use `chatbotIdentify()` early in the user session for better conversation tracking

## Integration Examples

### Dynamic Chatbot Selection Based on Page

```javascript
// Switch chatbots based on the current page
window.chatbotLoaded(() => {
  const currentPath = window.location.pathname;

  if (currentPath.includes("/support")) {
    wonderchat.changeChatbotId("support-bot-id");
  } else if (currentPath.includes("/sales")) {
    wonderchat.changeChatbotId("sales-bot-id");
  } else {
    wonderchat.changeChatbotId("general-bot-id");
  }
});
```

### User Authentication Integration

```javascript
// Integrate with your authentication system
async function handleUserAuthentication() {
  const user = await getCurrentUser(); // Your auth function

  if (user) {
    // Identify the user in Wonderchat with all available data
    wonderchat.chatbotIdentify({
      email: user.email,
      name: user.displayName,
      phoneNumber: user.phoneNumber,
      custom: {
        userId: user.id,
        accountType: user.accountType,
        registeredAt: user.createdAt
      }
    });

    // Optionally open the chat for logged-in users
    wonderchat.toggleChat(true);
  }
}
```

### Custom Chat Launcher

```javascript
// Create a custom button to control the chat
const customChatButton = document.createElement("button");
customChatButton.textContent = "Need Help?";
customChatButton.onclick = () => wonderchat.toggleChat();
document.body.appendChild(customChatButton);
```

## Troubleshooting

If the SDK functions are not working:

1. Verify the Wonderchat widget script is properly embedded
2. Check the browser console for any errors
3. Ensure you're calling the functions after the widget has loaded
4. Confirm you're using the correct chatbot IDs

For additional support, contact us at <support@wonderchat.io>
