🛠️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 globally 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
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:
window.changeChatbotId(chatbotId);
Parameters:
chatbotId
(string, required): The ID of the chatbot you want to switch to
Example:
// Switch to a different chatbot
window.changeChatbotId("your-new-chatbot-id");
// Example: Switch chatbot based on user selection
function switchToSupportBot() {
window.changeChatbotId("support-bot-123");
}
function switchToSalesBot() {
window.changeChatbotId("sales-bot-456");
}
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:
window.toggleChat(show);
Parameters:
show
(boolean, optional):true
: Opens the chat widgetfalse
: Closes the chat widgetIf omitted: Toggles the current state
Examples:
// Toggle the chat widget state
window.toggleChat();
// Explicitly open the chat widget
window.toggleChat(true);
// Explicitly close the chat widget
window.toggleChat(false);
// Example: Open chat when user clicks a help button
document.getElementById("help-button").addEventListener("click", () => {
window.toggleChat(true);
});
chatbotIdentify()
Sets the identified user's email address for the current chat session. This helps in tracking conversations and providing personalized support.
Syntax:
window.chatbotIdentify(params);
Parameters:
params
(object, required): An object containing user identification dataemail
(string, required): The user's email address
Examples:
// Identify a user by email
window.chatbotIdentify({ email: "[email protected]" });
// Example: Identify user after login
function onUserLogin(userData) {
// Your login logic here
// Identify the user in Wonderchat
window.chatbotIdentify({ email: userData.email });
}
// Example: Identify user from a form submission
document.getElementById("email-form").addEventListener("submit", (e) => {
e.preventDefault();
const email = document.getElementById("email-input").value;
window.chatbotIdentify({ email: email });
});
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:
window.clearChatbotHistory();
Parameters:
None
Examples:
// Clear chat history and start a new session
window.clearChatbotHistory();
// Example: Clear history when user clicks a "New Chat" button
document.getElementById("new-chat-button").addEventListener("click", () => {
window.clearChatbotHistory();
});
// Example: Clear history after completing a transaction
function onTransactionComplete() {
// Your transaction logic here
// Start a fresh chat session
window.clearChatbotHistory();
window.toggleChat(true); // Optionally open the chat
}
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:
window.prefillChatbotQuestion(question);
Parameters:
question
(string, required): The text to prefill in the chatbot's input field
Examples:
// Prefill a question
window.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");
window.prefillChatbotQuestion(question);
window.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]) {
window.prefillChatbotQuestion(questions[feature]);
window.toggleChat(true);
}
}
// Example: Prefill question from URL parameter
const urlParams = new URLSearchParams(window.location.search);
const question = urlParams.get("question");
if (question) {
window.chatbotLoaded(() => {
window.prefillChatbotQuestion(decodeURIComponent(question));
window.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
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:// Use the chatbotLoaded callback to ensure the widget is ready window.chatbotLoaded(() => { // SDK functions are now available window.chatbotIdentify({ email: "[email protected]" }); window.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 {
window.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
document.addEventListener("DOMContentLoaded", () => {
const currentPath = window.location.pathname;
if (currentPath.includes("/support")) {
window.changeChatbotId("support-bot-id");
} else if (currentPath.includes("/sales")) {
window.changeChatbotId("sales-bot-id");
} else {
window.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 && user.email) {
// Identify the user in Wonderchat
window.chatbotIdentify({ email: user.email });
// Optionally open the chat for logged-in users
window.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 = () => window.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 [email protected]
Last updated
Was this helpful?