BadgerFy.ai Docs

Conversion Tracking

Conversion tracking allows you to attribute orders and conversions to specific AI agent interactions. When a user engages with one of your agents and later completes a purchase, you can record that conversion to measure the direct impact of your AI agents on revenue.

⚡ Pro & Business Plans Only: Conversion tracking is available exclusively on Pro and Business plans. Upgrade your subscription to access this feature.

How It Works

BadgerFy.ai automatically tracks user engagements with your AI agents in the browser's local storage. Each engagement is stored with a 30-day expiration window. When a conversion occurs (typically on an order confirmation page), you call the recordConversionfunction to send the engagement data along with order details to your analytics.

  1. User Engages: A user interacts with one of your AI agents (assistant, quiz, nudge, exit-offer, or recommendation strip).
  2. Engagement Stored: The engagement is automatically recorded in local storage with a 30-day expiration.
  3. Conversion Occurs: The user completes a purchase on your site.
  4. Record Conversion: On your order confirmation page, call recordConversion with the order details.
  5. Analytics Updated: The conversion is attributed to all agents the user engaged with, and the engagement data is cleared.

Engagement Actions by Agent Type

Each agent type has specific actions that qualify as an engagement. These engagements are automatically tracked when the user performs the corresponding action:

AI Assistant

Action: chat-engagement

An engagement is recorded when a user sends their first message and receives a response from the AI Assistant. Simply opening the chat widget does not count as an engagement—there must be an actual conversation.

Quiz

Action: quiz-completed

An engagement is recorded when a user completes the quiz and views their personalized results. Starting or partially completing a quiz does not count as an engagement.

Nudge

Action: nudge-cta-click

An engagement is recorded when a user clicks the call-to-action (CTA) button on a nudge. Simply viewing the nudge does not count as an engagement.

Recommendation Strip

Action: product-clicked

An engagement is recorded when a user clicks on a product link within the recommendation strip. Viewing the strip without clicking a product does not count as an engagement.

Survey

Action: survey-result

An engagement is recorded when a user completes a survey by submitting a rating (star rating) or selecting a sentiment (emoji reaction). Simply viewing or dismissing a survey does not count as an engagement.

Engagement Storage

Engagements are stored in the browser's local storage under the key badgerfyai_engagements. Each engagement record includes:

  • agentId - The unique identifier of the agent
  • agentType - The type of agent (assistant, quiz, nudge, exit-offer, recommendation-strip, survey)
  • engagementAction - The specific action that triggered the engagement
  • engagedAt - Timestamp of when the engagement occurred
  • expiresAt - Timestamp when the engagement expires (30 days)
  • pagePath - The page path where the engagement occurred
ℹ️ 30-Day Window: Engagements automatically expire after 30 days. If a user engaged with an agent more than 30 days ago and then converts, that engagement will not be attributed.

Recording Conversions

To record a conversion, call the recordConversion function from your order confirmation page. This function sends analytics events for each stored engagement and then clears the engagement data.

Basic Conversion Recording

// On your order confirmation page
const result = await window.badgerfyai.recordConversion({
orderId: 'ORD-12345',
orderValue: '299.99'
});
console.log(result);
// { success: true, message: 'Recorded 2 of 2 conversion(s)', recorded: 2, errors: [] }

Conversion with Product Details

For more detailed analytics, you can include product information with your conversion:

// Record conversion with full product details
const result = await window.badgerfyai.recordConversion({
orderId: 'ORD-12345',
orderValue: '549.98',
products: [
{
productName: 'Wireless Gaming Mouse',
sku: 'WGM-001',
price: '79.99',
quantity: 1,
category: 'Peripherals'
},
{
productName: 'Mechanical Keyboard',
sku: 'MK-PRO-002',
price: '149.99',
quantity: 1,
category: 'Peripherals'
},
{
productName: 'USB-C Hub',
sku: 'HUB-7P',
price: '39.99',
quantity: 2,
category: 'Accessories'
}
]
});

Function Parameters

The recordConversion function accepts an object with the following properties:

PropertyTypeRequiredDescription
orderIdstringYesUnique identifier for the order
orderValuestringYesTotal order value as a decimal string (e.g., "1299.99")
productsarrayNoArray of product objects (see below)

Product Object Structure

Each product in the products array should have the following properties:

PropertyTypeRequiredDescription
productNamestringYesName of the product
skustringYesProduct SKU or identifier
pricestringYesUnit price as a decimal string (e.g., "29.99")
quantitynumberYesQuantity purchased
categorystringYesProduct category

Static Website Implementation

For static HTML websites, add the conversion tracking code to your order confirmation page:

<!-- Order Confirmation Page -->
<script>
// Wait for BadgerFy.ai to load
function recordOrderConversion() {
if (typeof window.badgerfyai === 'undefined') {
// Script not loaded yet, retry after a short delay
setTimeout(recordOrderConversion, 500);
return;
}
// Get order data from your page (example using data attributes)
const orderData = {
orderId: document.getElementById('order-id').textContent,
orderValue: document.getElementById('order-total').dataset.value,
products: JSON.parse(document.getElementById('order-products').dataset.products)
};
window.badgerfyai.recordConversion(orderData)
.then(result => {
console.log('Conversion recorded:', result);
})
.catch(error => {
console.error('Failed to record conversion:', error);
});
}
// Start the conversion recording process when the page loads
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', recordOrderConversion);
} else {
recordOrderConversion();
}
</script>

Next.js / React Implementation

For React-based applications, record the conversion in a useEffect hook on your order confirmation page:

// pages/order-confirmation.js
import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
export default function OrderConfirmation() {
const router = useRouter();
const { orderId } = router.query;
const [order, setOrder] = useState(null);
const [conversionRecorded, setConversionRecorded] = useState(false);
// Fetch order details
useEffect(() => {
if (orderId) {
fetchOrderDetails(orderId).then(setOrder);
}
}, [orderId]);
// Record conversion when order is loaded
useEffect(() => {
if (!order || conversionRecorded) return;
const recordConversion = async () => {
// Wait for BadgerFy.ai to be available
if (typeof window.badgerfyai === 'undefined') {
setTimeout(recordConversion, 500);
return;
}
try {
const result = await window.badgerfyai.recordConversion({
orderId: order.id,
orderValue: order.total.toFixed(2),
products: order.items.map(item => ({
productName: item.name,
sku: item.sku,
price: item.price.toFixed(2),
quantity: item.quantity,
category: item.category
}))
});
console.log('Conversion recorded:', result);
setConversionRecorded(true);
} catch (error) {
console.error('Failed to record conversion:', error);
}
};
recordConversion();
}, [order, conversionRecorded]);
if (!order) {
return <div>Loading order details...</div>;
}
return (
<div>
<h1>Thank you for your order!</h1>
<p>Order ID: {order.id}</p>
{/* Rest of your confirmation page */}
</div>
);
}
async function fetchOrderDetails(orderId) {
// Your order fetching logic
const response = await fetch(`/api/orders/${orderId}`);
return response.json();
}

Shopify Implementation

For Shopify stores, add conversion tracking to your order confirmation (thank you) page using the Checkout Settings:

Setup Steps

  1. Go to Settings → Checkout in your Shopify admin
  2. Scroll to Order status page section
  3. In the Additional scripts field, add the following code:
{% if first_time_accessed %}
<script>
// Wait for BadgerFy.ai to load
function recordShopifyConversion() {
if (typeof window.badgerfyai === 'undefined') {
setTimeout(recordShopifyConversion, 500);
return;
}
window.badgerfyai.recordConversion({
orderId: '{{ order.order_number }}',
orderValue: '{{ checkout.total_price | money_without_currency | remove: "," }}',
products: [
{% for line_item in checkout.line_items %}
{
productName: {{ line_item.product.title | json }},
sku: {{ line_item.sku | json }},
price: '{{ line_item.final_price | money_without_currency | remove: "," }}',
quantity: {{ line_item.quantity }},
category: {{ line_item.product.type | json }}
}{% unless forloop.last %},{% endunless %}
{% endfor %}
]
}).then(result => {
console.log('BadgerFy conversion recorded:', result);
}).catch(err => {
console.error('BadgerFy conversion error:', err);
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', recordShopifyConversion);
} else {
recordShopifyConversion();
}
</script>
{% endif %}
ℹ️ First Time Only: The first_time_accessed condition ensures the conversion is only recorded once, even if the customer refreshes the order confirmation page.

BigCommerce Implementation

For BigCommerce stores, add conversion tracking to your order confirmation page using the Script Manager or by editing your theme files.

Method 1: Script Manager

  1. Go to Storefront → Script Manager in your BigCommerce admin
  2. Click Create a Script
  3. Configure the script:
    • Name: BadgerFy Conversion Tracking
    • Location: Footer
    • Pages: Order Confirmation
    • Script type: Script
  4. Paste the following code:
<script>
(function() {
function recordBigCommerceConversion() {
if (typeof window.badgerfyai === 'undefined') {
setTimeout(recordBigCommerceConversion, 500);
return;
}
// BigCommerce provides order data in the page context
// Access via Stencil's injected JSON or data attributes
var orderData = window.BCData && window.BCData.order;
if (!orderData) {
// Alternative: try to get from page elements
var orderIdEl = document.querySelector('[data-order-id]');
var orderTotalEl = document.querySelector('[data-order-total]');
if (orderIdEl && orderTotalEl) {
orderData = {
id: orderIdEl.dataset.orderId,
total: orderTotalEl.dataset.orderTotal
};
}
}
if (!orderData) {
console.log('BadgerFy: No order data found');
return;
}
var products = [];
if (orderData.items && orderData.items.length) {
orderData.items.forEach(function(item) {
products.push({
productName: item.name || item.product_name,
sku: item.sku || item.product_id,
price: (item.price || item.base_price || 0).toString(),
quantity: item.quantity || 1,
category: item.category || 'Product'
});
});
}
window.badgerfyai.recordConversion({
orderId: orderData.id || orderData.order_id,
orderValue: (orderData.total || orderData.grand_total || 0).toString(),
products: products
}).then(function(result) {
console.log('BadgerFy conversion recorded:', result);
}).catch(function(err) {
console.error('BadgerFy conversion error:', err);
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', recordBigCommerceConversion);
} else {
recordBigCommerceConversion();
}
})();
</script>

Method 2: Stencil Theme

For more control, edit your Stencil theme's order confirmation template:

{{! templates/pages/order-confirmation.html }}
{{#if order}}
<script>
(function() {
function recordConversion() {
if (typeof window.badgerfyai === 'undefined') {
setTimeout(recordConversion, 500);
return;
}
window.badgerfyai.recordConversion({
orderId: '{{order.id}}',
orderValue: '{{order.grand_total.value}}',
products: [
{{#each order.items}}
{
productName: {{{json name}}},
sku: {{{json sku}}},
price: '{{price.value}}',
quantity: {{quantity}},
category: {{{json category}}}
}{{#unless @last}},{{/unless}}
{{/each}}
]
}).then(function(result) {
console.log('BadgerFy conversion recorded:', result);
}).catch(function(err) {
console.error('BadgerFy conversion error:', err);
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', recordConversion);
} else {
recordConversion();
}
})();
</script>
{{/if}}
ℹ️ Theme Customization: Editing Stencil theme files requires familiarity with BigCommerce's theme development. Use the Script Manager method if you prefer a code-free approach.

Adobe Commerce (Magento) Implementation

For Adobe Commerce (Magento 2) stores, add conversion tracking using a custom module or by editing the success page template.

Method 1: Template Override

Create a template override for the checkout success page. Add this file to your theme:

app/design/frontend/[Vendor]/[theme]/Magento_Checkout/templates/success.phtml

<?php
/**
* BadgerFy.ai Conversion Tracking for Magento 2
* Add this to your success.phtml template
*/
/** @var \Magento\Checkout\Block\Onepage\Success $block */
$order = $block->getOrder();
if ($order):
$items = [];
foreach ($order->getAllVisibleItems() as $item) {
$items[] = [
'productName' => $item->getName(),
'sku' => $item->getSku(),
'price' => number_format($item->getPrice(), 2, '.', ''),
'quantity' => (int) $item->getQtyOrdered(),
'category' => '' // Add category logic if needed
];
}
?>
<script>
(function() {
function recordMagentoConversion() {
if (typeof window.badgerfyai === 'undefined') {
setTimeout(recordMagentoConversion, 500);
return;
}
window.badgerfyai.recordConversion({
orderId: '<?= $block->escapeJs($order->getIncrementId()) ?>',
orderValue: '<?= $block->escapeJs(number_format($order->getGrandTotal(), 2, '.', '')) ?>',
products: <?= json_encode($items) ?>
}).then(function(result) {
console.log('BadgerFy conversion recorded:', result);
}).catch(function(err) {
console.error('BadgerFy conversion error:', err);
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', recordMagentoConversion);
} else {
recordMagentoConversion();
}
})();
</script>
<?php endif; ?>

Method 2: Custom Module

For a cleaner implementation, create a custom module with an observer or use Layout XML to inject the tracking script:

<!-- app/code/Vendor/BadgerFy/view/frontend/layout/checkout_onepage_success.xml -->
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="content">
<block class="Vendor\BadgerFy\Block\ConversionTracking"
name="badgerfy.conversion.tracking"
template="Vendor_BadgerFy::conversion-tracking.phtml"
after="-"/>
</referenceContainer>
</body>
</page>
⚠️ Cache Clearing: After adding the template or module, clear the Magento cache: bin/magento cache:clean. You may also need to run bin/magento setup:upgrade for module changes.

Method 3: Google Tag Manager

If you have GTM installed, you can use the dataLayer to trigger conversion tracking. Add a custom HTML tag that fires on the order success page:

<script>
(function() {
function recordConversion() {
if (typeof window.badgerfyai === 'undefined') {
setTimeout(recordConversion, 500);
return;
}
// Get order data from dataLayer (requires Enhanced Ecommerce)
var orderData = null;
if (window.dataLayer) {
for (var i = 0; i < window.dataLayer.length; i++) {
var entry = window.dataLayer[i];
if (entry.ecommerce && entry.ecommerce.purchase) {
orderData = entry.ecommerce.purchase;
break;
}
}
}
if (!orderData || !orderData.actionField) {
console.log('BadgerFy: No purchase data in dataLayer');
return;
}
var products = (orderData.products || []).map(function(p) {
return {
productName: p.name,
sku: p.id || p.sku,
price: (p.price || 0).toString(),
quantity: p.quantity || 1,
category: p.category || 'Product'
};
});
window.badgerfyai.recordConversion({
orderId: orderData.actionField.id,
orderValue: (orderData.actionField.revenue || 0).toString(),
products: products
}).then(function(result) {
console.log('BadgerFy conversion recorded:', result);
}).catch(function(err) {
console.error('BadgerFy conversion error:', err);
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', recordConversion);
} else {
recordConversion();
}
})();
</script>
ℹ️ Enhanced Ecommerce: The GTM method requires Enhanced Ecommerce or GA4 Ecommerce to be configured in your Magento store to populate the dataLayer with purchase data.

WooCommerce Implementation

For WooCommerce stores, add conversion tracking to your thank you page using WordPress hooks or a custom plugin.

Method 1: Functions.php

Add the following code to your theme's functions.php file:

// Add BadgerFy.ai conversion tracking to WooCommerce thank you page
add_action('woocommerce_thankyou', 'badgerfy_record_conversion', 10, 1);
function badgerfy_record_conversion($order_id) {
if (!$order_id) return;
$order = wc_get_order($order_id);
if (!$order) return;
// Only run once per order
if ($order->get_meta('_badgerfy_conversion_tracked')) return;
$items = array();
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$items[] = array(
'productName' => $item->get_name(),
'sku' => $product ? $product->get_sku() : '',
'price' => number_format($item->get_total() / $item->get_quantity(), 2, '.', ''),
'quantity' => $item->get_quantity(),
'category' => $product ? implode(', ', wp_get_post_terms($product->get_id(), 'product_cat', array('fields' => 'names'))) : ''
);
}
?>
<script>
(function() {
function recordConversion() {
if (typeof window.badgerfyai === 'undefined') {
setTimeout(recordConversion, 500);
return;
}
window.badgerfyai.recordConversion({
orderId: '<?php echo esc_js($order->get_order_number()); ?>',
orderValue: '<?php echo esc_js($order->get_total()); ?>',
products: <?php echo json_encode($items); ?>
}).then(function(result) {
console.log('BadgerFy conversion recorded:', result);
}).catch(function(err) {
console.error('BadgerFy conversion error:', err);
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', recordConversion);
} else {
recordConversion();
}
})();
</script>
<?php
// Mark as tracked to prevent duplicate conversions
$order->update_meta_data('_badgerfy_conversion_tracked', true);
$order->save();
}

Method 2: Code Snippets Plugin

If you prefer not to edit theme files, install the Code Snippets plugin and add the same code as a new PHP snippet. This method survives theme updates.

⚠️ Child Theme Recommended: If editing functions.php directly, use a child theme to prevent losing your changes during theme updates.

Wix Implementation

For Wix stores using Wix eCommerce, add conversion tracking using Velo by Wix (formerly Corvid).

Setup Steps

  1. Enable Dev Mode by clicking Dev Mode in your editor toolbar
  2. Go to your Thank You page (usually Thank You Page in the Pages panel under Store Pages)
  3. Click + Add Code and add the following to the page:
// Thank You Page Code (Wix Velo)
import wixWindow from 'wix-window';
$w.onReady(function () {
// Get order data from the page
// Note: Adjust selectors based on your Thank You page elements
const orderData = wixWindow.getRouterData();
if (orderData && orderData.orderId) {
recordBadgerFyConversion(orderData);
}
});
async function recordBadgerFyConversion(orderData) {
// Wait for BadgerFy.ai to load
const checkBadgerFy = () => {
return new Promise((resolve) => {
const check = () => {
if (typeof window.badgerfyai !== 'undefined') {
resolve();
} else {
setTimeout(check, 500);
}
};
check();
});
};
await checkBadgerFy();
try {
const result = await window.badgerfyai.recordConversion({
orderId: orderData.orderId,
orderValue: orderData.totals.total.toString(),
products: orderData.lineItems.map(item => ({
productName: item.name,
sku: item.sku || item.productId,
price: item.price.toString(),
quantity: item.quantity,
category: item.productType || 'Product'
}))
});
console.log('BadgerFy conversion recorded:', result);
} catch (err) {
console.error('BadgerFy conversion error:', err);
}
}
ℹ️ Wix Velo Required: Conversion tracking on Wix requires Velo (Dev Mode) which is available on Premium Wix plans. The exact order data structure may vary based on your Wix eCommerce setup.

Squarespace Implementation

For Squarespace Commerce stores, add conversion tracking using the Order Confirmation page code injection.

Setup Steps

  1. Go to Settings → Advanced → Code Injection
  2. In the Order Confirmation Page section, paste the following code:
<script>
(function() {
function recordSquarespaceConversion() {
if (typeof window.badgerfyai === 'undefined') {
setTimeout(recordSquarespaceConversion, 500);
return;
}
// Squarespace provides order data in Y.Squarespace.Commerce object
var commerce = window.Y && window.Y.Squarespace && window.Y.Squarespace.Commerce;
if (!commerce || !commerce.currentOrder) {
console.log('BadgerFy: No order data found');
return;
}
var order = commerce.currentOrder;
var products = [];
if (order.items && order.items.length) {
order.items.forEach(function(item) {
products.push({
productName: item.productName || item.title,
sku: item.sku || item.productId,
price: (item.unitPrice / 100).toFixed(2),
quantity: item.quantity,
category: item.productType || 'Product'
});
});
}
window.badgerfyai.recordConversion({
orderId: order.orderNumber || order.id,
orderValue: (order.grandTotal / 100).toFixed(2),
products: products
}).then(function(result) {
console.log('BadgerFy conversion recorded:', result);
}).catch(function(err) {
console.error('BadgerFy conversion error:', err);
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', recordSquarespaceConversion);
} else {
recordSquarespaceConversion();
}
})();
</script>
⚠️ Business Plan Required: Order Confirmation Page code injection on Squarespace requires a Commerce plan (Basic Commerce or Advanced Commerce). The code above uses Squarespace's internal commerce object which may change with Squarespace updates.

Alternative: Manual Data Attributes

If the automatic method doesn't work, you can add data attributes to your Order Confirmation page template and read from those:

<script>
(function() {
function recordConversion() {
if (typeof window.badgerfyai === 'undefined') {
setTimeout(recordConversion, 500);
return;
}
// Read from URL parameters if Squarespace adds them
var urlParams = new URLSearchParams(window.location.search);
var orderId = urlParams.get('orderNumber') ||
document.querySelector('[data-order-id]')?.dataset.orderId;
var orderValue = urlParams.get('orderTotal') ||
document.querySelector('[data-order-total]')?.dataset.orderTotal;
if (!orderId || !orderValue) {
console.log('BadgerFy: Could not find order data');
return;
}
window.badgerfyai.recordConversion({
orderId: orderId,
orderValue: orderValue
}).then(function(result) {
console.log('BadgerFy conversion recorded:', result);
}).catch(function(err) {
console.error('BadgerFy conversion error:', err);
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', recordConversion);
} else {
recordConversion();
}
})();
</script>

Response Format

The recordConversion function returns a promise that resolves to a result object:

// Success response
{
success: true,
message: 'Recorded 2 of 2 conversion(s)',
recorded: 2, // Number of conversions successfully recorded
errors: [] // Array of any errors encountered
}
// Partial success (some engagements failed to record)
{
success: true,
message: 'Recorded 1 of 2 conversion(s)',
recorded: 1,
errors: ['Failed to record conversion for agent 456: Network error']
}
// No engagements to record
{
success: true,
message: 'No agent engagements found to convert',
recorded: 0,
errors: []
}
// Validation error
{
success: false,
message: 'orderId is required',
recorded: 0,
errors: ['orderId is required']
}

Disabling Default Engagements

By default, BadgerFy.ai automatically tracks engagements for all agent types. If you want to manually control when engagements are recorded, you can disable the default tracking:

// Disable default engagement tracking
window.badgerfyaiConfig = {
engagementConfig: {
disableDefaultEngagements: true
}
};
// Then manually record engagements when needed
window.badgerfyai.addAgentEngagement(agentId, 'custom-action');

Engagement Helper Functions

BadgerFy.ai exposes several helper functions for managing engagements:

Available Functions

// Check if a user has engaged with a specific agent
const hasEngaged = window.badgerfyai.hasAgentEngagement(agentId);
// Returns: boolean
// Get engagement details for a specific agent
const engagement = window.badgerfyai.getAgentEngagement(agentId);
// Returns: engagement object or null
// Get all current engagements
const allEngagements = window.badgerfyai.getAllAgentEngagements();
// Returns: array of engagement objects
// Manually add an engagement
window.badgerfyai.addAgentEngagement(agentId, 'custom-action');
// Returns: boolean (true if added, false if already exists)
// Clear engagement for a specific agent
window.badgerfyai.clearAgentEngagement(agentId);
// Returns: boolean
// Clear all engagements
window.badgerfyai.clearAllAgentEngagements();
// Returns: boolean
// Remove expired engagements (called automatically on page load)
window.badgerfyai.cleanupExpiredEngagements();

Lifecycle Callbacks

BadgerFy.ai provides two lifecycle callbacks that you can use to integrate with your application's logic. Define these in your configuration before the script loads.

onLoad Callback

The onLoad callback fires when the BadgerFy.ai script has fully loaded and initialized. This is useful for triggering actions that depend on BadgerFy.ai being ready.

window.badgerfyaiConfig = {
onLoad: () => {
console.log('BadgerFy.ai is ready!');
// Example: Track that BadgerFy is active in your analytics
analytics.track('BadgerFy Loaded');
// Example: Update UI state
setIsBadgerFyReady(true);
// Example: Access BadgerFy.ai API
const agents = window.badgerfyai.getAgents();
console.log('Active agents:', agents);
}
};

onEngagement Callback

The onEngagement callback fires whenever a user engagement is recorded. This allows you to react to engagements in real-time, such as sending data to your own analytics platform or triggering custom logic.

window.badgerfyaiConfig = {
onEngagement: ({ agentId, agentType, engagementAction, pagePath }) => {
console.log('User engaged!', { agentId, agentType, engagementAction, pagePath });
// Example: Send to your analytics platform
analytics.track('BadgerFy Engagement', {
agentId,
agentType,
action: engagementAction,
page: pagePath
});
// Example: Trigger a custom event
window.dispatchEvent(new CustomEvent('badgerfy:engagement', {
detail: { agentId, agentType, engagementAction, pagePath }
}));
}
};

Callback Parameters

The onEngagement callback receives an object with the following properties:

PropertyTypeDescription
agentIdstringThe unique identifier of the agent that was engaged with
agentTypestringThe type of agent (assistant, quiz, nudge, exit-offer, recommendation-strip, survey)
engagementActionstringThe action that triggered the engagement (e.g., chat-engagement, quiz-completed)
pagePathstringThe page path where the engagement occurred

Combined Configuration Example

Here's a complete example showing both callbacks along with other configuration options:

window.badgerfyaiConfig = {
// Lifecycle callbacks
onLoad: () => {
console.log('BadgerFy.ai initialized');
},
onEngagement: ({ agentId, agentType, engagementAction, pagePath }) => {
// Send to Google Analytics 4
gtag('event', 'badgerfy_engagement', {
agent_id: agentId,
agent_type: agentType,
engagement_action: engagementAction,
page_path: pagePath
});
},
// Optional: Disable default engagement tracking
// disableDefaultEngagements: true,
// Optional: Tool call handlers
functions: [
{
pageAgentId: 'YOUR_AGENT_ID',
functionName: 'addToCart',
functionCall: async (params) => {
// Your logic here
return { success: true };
}
}
]
};

Best Practices

  • Record Once: Only call recordConversion once per order. The function clears engagement data after recording, so subsequent calls will have no engagements to record.
  • Handle Errors: Always wrap the conversion call in a try/catch block to handle network errors or other issues gracefully.
  • Valid Order Values: Ensure orderValue is formatted as a decimal string (e.g., "99.99", "1250.00"). Invalid formats will be rejected.
  • Wait for Script: The BadgerFy.ai script loads asynchronously. Always check that window.badgerfyai is defined before calling functions.
  • Test Thoroughly: Use browser developer tools to inspect local storage (badgerfyai_engagements) and verify engagements are being tracked correctly before deploying.