Skip to content

Client-Side Custom Actions

Client-Side Custom Actions

Overview

Client-Side Custom Actions allow your Nexvio.ai chatbot to trigger JavaScript functions directly in the user’s browser. This powerful feature enables your chatbot to interact with your website’s content, manipulate the DOM, trigger animations, redirect users, and much more.

How It Works

  1. You define JavaScript functions on your website that perform specific actions
  2. You configure your chatbot to trigger these functions at appropriate moments in the conversation
  3. When triggered, your code executes in the user’s browser with any parameters passed from the chatbot

Setting Up Client-Side Custom Actions

Step 1: Define Your Custom Functions

First, define the functions you want your chatbot to be able to call. These should be added to your website before the Nexvio.ai embed code:

// Add this code before the Nexvio.ai embed script
window.nexvioCustomActions = {
// Navigate to a specific URL
navigate: function(params) {
window.location.href = params.url;
},
// Show a specific product
showProduct: function(params) {
document.getElementById('product-modal').style.display = 'block';
document.getElementById('product-title').innerText = params.title;
document.getElementById('product-description').innerText = params.description;
document.getElementById('product-image').src = params.imageUrl;
},
// Add item to shopping cart
addToCart: function(params) {
// Your cart logic here
console.log('Adding to cart:', params.productId, 'Quantity:', params.quantity);
// Call your existing cart function
yourExistingAddToCartFunction(params.productId, params.quantity);
// Show confirmation
alert('Added ' + params.productName + ' to your cart!');
}
};

Step 2: Configure Your Chatbot

In your Nexvio.ai dashboard:

  1. Navigate to your chatbot’s settings
  2. Go to the “Custom Actions” section
  3. Enable “Client-Side Custom Actions”
  4. Add the names of your custom functions (e.g., “navigate”, “showProduct”, “addToCart”)

Step 3: Train Your Chatbot

Update your chatbot’s training to include instructions on when to use these custom actions. For example:

When a user asks to see a specific product, use the showProduct custom action with the appropriate product details.
When a user wants to navigate to a specific page, use the navigate custom action with the appropriate URL.
When a user wants to add a product to their cart, use the addToCart custom action with the product ID, name, and quantity.

Examples

Example 1: Page Navigation

window.nexvioCustomActions = {
// Navigate to pages within your site
navigateToPage: function(params) {
// You can add validation or transformations here
if (params.page === 'pricing') {
window.location.href = '/pricing';
} else if (params.page === 'features') {
window.location.href = '/features';
} else if (params.page === 'contact') {
window.location.href = '/contact';
} else {
// Default to homepage if unknown page
window.location.href = '/';
}
}
};

Example 2: Form Prefilling

window.nexvioCustomActions = {
// Prefill a contact form based on conversation
prefillContactForm: function(params) {
if (params.name) {
document.getElementById('contact-name').value = params.name;
}
if (params.email) {
document.getElementById('contact-email').value = params.email;
}
if (params.inquiry) {
document.getElementById('contact-message').value = params.inquiry;
}
// Optionally scroll to the form
document.getElementById('contact-form').scrollIntoView({
behavior: 'smooth'
});
}
};

Example 3: Interactive Product Filtering

window.nexvioCustomActions = {
// Filter product display based on user preferences
filterProducts: function(params) {
// Hide all products first
const allProducts = document.querySelectorAll('.product-item');
allProducts.forEach(product => {
product.style.display = 'none';
});
// Build selector based on filters
let selector = '.product-item';
if (params.category) {
selector += '[data-category="' + params.category + '"]';
}
if (params.minPrice) {
selector += '[data-price>="' + params.minPrice + '"]';
}
if (params.maxPrice) {
selector += '[data-price<="' + params.maxPrice + '"]';
}
// Show filtered products
const filteredProducts = document.querySelectorAll(selector);
filteredProducts.forEach(product => {
product.style.display = 'block';
});
// Update filter UI if it exists
if (document.getElementById('active-filters')) {
document.getElementById('active-filters').innerText =
'Filtered by: ' + Object.entries(params).map(([k,v]) => `${k}: ${v}`).join(', ');
}
}
};

Advanced Usage

Returning Values to the Chatbot

Your custom actions can optionally return values that will be passed back to the chatbot:

window.nexvioCustomActions = {
getUserPreferences: function() {
// Get user preferences from localStorage or cookies
const preferences = {
theme: localStorage.getItem('userTheme') || 'light',
recentlyViewed: JSON.parse(localStorage.getItem('recentlyViewed') || '[]'),
currency: localStorage.getItem('currency') || 'USD'
};
// Return these to the chatbot
return preferences;
}
};

The chatbot can then use this information to provide more personalized responses.

Handling Asynchronous Operations

For actions that involve asynchronous operations, you can return promises:

window.nexvioCustomActions = {
checkInventory: async function(params) {
try {
const response = await fetch('/api/inventory/' + params.productId);
const data = await response.json();
return {
inStock: data.quantity > 0,
quantity: data.quantity,
estimatedShipping: data.estimatedShipping
};
} catch (error) {
console.error('Error checking inventory:', error);
return {
error: 'Could not check inventory',
inStock: false
};
}
}
};

Security Considerations

When implementing client-side custom actions, keep these security best practices in mind:

  1. Validate Input: Always validate any parameters received from the chatbot before using them in your functions.
  2. Avoid Sensitive Operations: Don’t perform sensitive operations like payments directly from custom actions.
  3. Cross-Site Scripting (XSS): Be careful when inserting content from parameters into your DOM to avoid XSS vulnerabilities.
  4. Avoid eval(): Never use eval() or similar functions with data from the chatbot.
  5. Limit Permissions: Only expose functions that perform actions appropriate for a chatbot to trigger.

Debugging Custom Actions

You can debug your custom actions by adding console logs and monitoring the browser’s developer console:

window.nexvioCustomActions = {
debuggableAction: function(params) {
console.log('Custom action triggered with parameters:', params);
try {
// Your action code here
const result = performAction(params);
console.log('Action completed successfully with result:', result);
return result;
} catch (error) {
console.error('Error in custom action:', error);
return { error: error.message };
}
}
};

Best Practices

  1. Keep Actions Focused: Each custom action should perform a single, well-defined task.
  2. Handle Errors Gracefully: Implement proper error handling to prevent your website from breaking if something goes wrong.
  3. Provide Feedback: Give users visual feedback when actions are executed.
  4. Test Thoroughly: Test your custom actions with various inputs to ensure they work correctly.
  5. Documentation: Document your custom actions so other developers can understand what they do and how to use them.