Skip to main content

API Reference

Kameleoon.API.Core

This module contains essential functions for implementing front-end A/B testing variations without flickering. Use these methods in the prescribed order for optimal results. The module also includes engine initialization methods, such as those related to privacy laws and legal consent collection.

Before calling the Activation API JavaScript object, it's important to verify the Kameleoon Engine has loaded. Use the Kameleoon Command Queue for delayed command execution when performing actions like sending tracking data, triggering experiments, or updating visitor attributes. Passed commands and functions execute immediately if the engine is loaded; otherwise, they enter a queue for later execution. Refer to the Command queue documentation for more information.

enableLegalConsent

var agreedButton = Kameleoon.API.Utils.querySelectorAll("#agreed")[0];

Kameleoon.API.Utils.addEventListener(agreedButton, "mousedown", function (event) {
Kameleoon.API.Core.enableLegalConsent();
});

The enableLegalConsent() method should be called after obtaining legal consent from the visitor to activate Kameleoon. This method activates Kameleoon's normal operation mode. For more information, refer to the Consent management article.

Arguments
NameTypeDescription
moduleStringName of the module to enable: "PRODUCT_RECOMMENDATION", "AB_TESTING", "PERSONALIZATION", or "BOTH". For example, PRODUCT_RECOMMENDATION executes the entry point exclusively with product recommendation capabilities. AB_TESTING enables A/B testing and product recommendation (unless the custom option to differentiate consent is active). OTH enables all capabilities. If omitted, the method activates legal consent for all modules (BOTH) by default.
note

A custom option is also available that allows separate management of Product Recommendation consent. When this option is active, explicitly call enableLegalConsent("PRODUCT_RECOMMENDATION") to activate the module. Contact the Customer Success Manager to enable this feature.

disableLegalConsent

var disableButton = Kameleoon.API.Utils.querySelectorAll("#disable")[0];

Kameleoon.API.Utils.addEventListener(disableButton, "mousedown", function (event) {
Kameleoon.API.Core.disableLegalConsent();
});

The disableLegalConsent() method should be called when a visitor declines the use of Kameleoon. This method disables normal operation mode. Refer to the Consent management article for more information.

Arguments
NameTypeDescription
moduleStringName of the module to disable: "AB_TESTING", "PERSONALIZATION", or "BOTH". If omitted, the method disables legal consent for all modules (BOTH).
note

A custom option is also available that allows separate management of Product Recommendation consent. When this option is active, explicitly call disableLegalConsent("PRODUCT_RECOMMENDATION") to disable the module. Contact the Customer Success Manager to enable this feature.

enableSinglePageSupport

if (location.href.indexOf("mySPAWebsitePart") != -1) {
Kameleoon.API.Core.enableSinglePageSupport();
}

The enableSinglePageSupport() method reloads the Kameleoon engine when the active URL changes, regardless of browser page loads. Use this method for Single Page Applications (SPAs) with multiple URLs and a single initial load. Kameleoon treats each URL change as a new page, enabling URL targeting and accurate tracking of metrics like page views.

note

Kameleoon will also automatically remove all elements that have been added on the page that use HTML IDs that begin with "kameleoonElement" or "kameleoonStyleSheet" when the SPA reloads.

enableDynamicRefresh

if (location.href.indexOf("cart") != -1) {
Kameleoon.API.Core.enableDynamicRefresh();
}

The enableDynamicRefresh() method detects element changes and reapplies Graphic Editor modifications. This method supports SPAs that dynamically modify the DOM without URL changes or page reloads, preventing dynamic updates from removing experiments. Refer to enableSinglePageSupport() for other SPA types.

getConfiguration

var configuration = Kameleoon.API.Core.getConfiguration();

if (configuration.siteCode == "abcde12345") {
document.cookie = "MyMainSite=true;";
} else if (configuration.siteCode == "12345abcdef") {
document.cookie = "MySubSite=true;";
}

The getConfiguration() method returns a reference to the Configuration object, which contains global constant values for the site's Kameleoon configuration.

Return value
NameTypeDescription
configurationObjectConfiguration object.

load

var href = location.href;

var intervalId = Kameleoon.API.Utils.setInterval(function () {
if (location.href != href) {
Kameleoon.API.Core.load();
}
}, 2000);

The load() method initializes the Kameleoon engine. While initialization typically occurs automatically during application file loading, manual calls are sometimes necessary. The example demonstrates implementing reloads after each URL change, similar to enableSinglePageSupport().

note

Kameleoon will also automatically remove all elements that have been added on the page that use HTML IDs that begin with "kameleoonElement" or "kameleoonStyleSheet" when the SPA reloads.

processRedirect

var experiment = Kameleoon.API.Experiments.getByName("RedirectExperiment");

if (experiment.associatedVariation.id == 123456) {
Kameleoon.API.Core.processRedirect("https://www.mywebsite.com?variation=A");
}

The processRedirect() method redirects the browser to another URL, typically for split A/B experiments. Use this method instead of window.location.href = redirectionURL; to ensure proper background tracking.

note

If the redirection URL is on a domain other than the base URL and the Kameleoon installation omits unified session data, the engine adds a kameleoonRedirect-{experimentID} parameter to the target URL to ensure accurate tracking.

Arguments
NameTypeDescription
redirectionURLStringURL for redirection. This field is mandatory.

runWhenConditionTrue

Kameleoon.API.Core.runWhenConditionTrue(function () {
return typeof jQuery != "undefined";
}, function () {
jQuery("#bloc-2345").text("Mon nouveau texte");
}, 200);

The runWhenConditionTrue() method executes the callback function when the conditionFunction returns true. The method uses a polling mechanism, which may cause flickering. Use runWhenElementPresent() instead for improved performance. Refer to the runWhenElementPresent() description for details.

Arguments
NameTypeDescription
conditionFunctionFunctionJavaScript function returning true or false. This field is mandatory.
callbackFunctionJavaScript function executing when the conditionFunction returns true. This field is mandatory.
pollingIntervalNumberThe engine executes the conditionFunction periodically at this interval. When runWhenElementPresent() is unavailable, a lower pollingInterval reduces flickering but increases CPU usage. If omitted, the method defaults to 200 milliseconds.

runWhenElementPresent

// With mutation observers management.
Kameleoon.API.Core.runWhenElementPresent("#bloc-2345", function (elements) {
elements[0].innerText = "My new Text";
});

// With multiple CSS selectors. Executes if any one of the elements is present.
Kameleoon.API.Core.runWhenElementPresent("#bloc-567, .cta-button, #bloc-789", function (elements) {
elements[0].innerText = "More new text";
});

// Without mutation observers management, Kameleoon polls every 200ms to check if the element is on the page.
Kameleoon.API.Core.runWhenElementPresent("#MyPopup.showed", function (elements) {
Kameleoon.API.Events.trigger("popup displayed");
}, 200);

// With mutation observers management and Single Page App support, Kameleoon applies modifications whenever new elements are added to the DOM or when there is a dynamic refresh of the Single Page App that removes previous modifications.
Kameleoon.API.Core.runWhenElementPresent(".product-button", function (elements) {
elements.forEach(element => {
element.innerText = "Add To Cart";
});
}, null, true);

The runWhenElementPresent() method executes the callback function when a specific element appears in the DOM. Utilizing Mutation Observers, this method powers Anti-Flickering technology. Identify the key elements for a variation and call runWhenElementPresent() using the element as the first argument and the implementation code as the callback. This ensures modifications execute as soon as the element appears, before the browser initiates a display refresh cycle.

To act on multiple elements, call runWhenElementPresent() separately for each element rather than targeting only the expected final element. A single call may result in flickering if a refresh cycle occurs between the appearance of different elements.

note

Providing this value disables Mutation Observers and Anti-Flickering, reverting to legacy polling. Use this argument only in specific cases, such as complex selector queries with high CPU impact.

Arguments
NameTypeDescription
selectorStringCSS selector of the element. To specify multiple CSS selectors, provide a single comma-separated string. The callback executes when one or more elements exist. This field is mandatory.
callbackFunctionJavaScript function to execute when the element appears in the DOM. This field is mandatory.
pollingIntervalNumberProviding this value disables Mutation Observers and reverts the engine to legacy polling, which may cause flickering. This field is optional.
isDynamicElementBooleanWhen active, Kameleoon tracks the selector if not immediately found at page load and executes the callback as elements appear. The callback triggers again for each new element matching the selector. This setting supports dynamic menus, infinite scrolling, and pop-ups. This field is optional.

runWhenShadowRootElementPresent

const wrapper = document.querySelector(".shadow-wrapper");
const shadow = wrapper.attachShadow({ mode: "open" });
const span = document.createElement("span");
span.classList.add("selector-inside-wrapper");
span.textContent = "I'm in the shadow DOM";
shadow.appendChild(span);

Kameleoon.API.Core.runWhenShadowRootElementPresent('.shadow-wrapper', '.selector-inside-wrapper', (elements) => {
elements[0].innerText = "New text"
});

The runWhenShadowRootElementPresent() method executes the callback function when a specific element appears in a shadow DOM set to mode: open.

Arguments

NameTypeDescription
parentSelectorStringCSS selector for the parent element. This field is mandatory.
shadowRootElementSelectorStringCSS selector inside the shadow DOM. This field is mandatory.
callbackFunctionJavaScript function to execute when the element appears in the shadow DOM. This field is mandatory.
isDynamicElementBooleanWhen active, Kameleoon tracks the selector if not immediately found and executes the callback as elements appear. The callback triggers again for each new element matching the selector. This setting supports dynamic menus, infinite scrolling, and pop-ups.

Kameleoon.API.Goals

This module manages goal triggering and conversion data, such as purchase confirmations and revenue registration.

cancelConversion

var buttons = Kameleoon.API.Utils.querySelectorAll(".btnRemoveFromCart");

buttons.forEach(function (button) {
Kameleoon.API.Utils.addEventListener(button, "mousedown", function (event) {
Kameleoon.API.Goals.cancelConversion(event.target.id);
});
});

The cancelConversion() method cancels a conversion triggered during the current visit. This method cannot cancel conversions from previous visits.

Arguments
NameTypeDescription
goalNameOrIDString or NumberName or ID of the goal as defined in the Kameleoon App. This field is mandatory.

processConversion

caution

Before implementing the processConversion, review the Custom Code for Custom Goal feature, which simplifies customization by removing the requirement for a goal ID.

//Conversion for "Add to cart" goal (goal id 123456)
Kameleoon.API.Core.runWhenElementPresent("#buyButton", ([buyButton]) => {
Kameleoon.API.Utils.addEventListener(buyButton, "click", () => {
Kameleoon.API.Goals.processConversion(123456); //Add to cart
});
});

//Conversion for "Add to cart" goal (goal id 123456) with optional revenue argument
Kameleoon.API.Core.runWhenElementPresent("#buyButton", ([buyButton]) => {
Kameleoon.API.Utils.addEventListener(buyButton, "click", () => {
Kameleoon.API.Goals.processConversion(123456, 19.99); //Add to cart
});
});

The processConversion() method triggers a conversion.

note

When initiating conversions from a Tag Management System (e.g., Google Tag Manager), use the Kameleoon Command Queue to delay execution until the engine loads. The engine processes queued commands in order after initialization. Example:

window.kameleoonQueue = window.kameleoonQueue || [];
kameleoonQueue.push(['Kameleoon.API.Goals.processConversion', 'GOAL_ID']);
Arguments
NameTypeDescription
goalNameOrIDString or NumberName or ID of the goal as defined in the Kameleoon App. Goal names must be unique. This field is mandatory.
revenueNumberTransaction amount. Providing this value enables Kameleoon to track purchase metrics, such as revenue and average cart amount. This field is optional.
metadataObjectSets specific values for custom data defined as goal metadata in the Kameleoon App. This field is optional.
note

Metadata values are accessible through raw data exports and the results page.

If providing the metadata parameter, Kameleoon uses these specified values for the current conversion instead of the values previously collected via setCustomData(). If the parameter is omitted, Kameleoon uses the last tracked values for the customData prior to the conversion within the same visit.

Kameleoon considers only the metadata values passed directly to the processConversion() method and ignores previously set Custom Data. In the following example, the conversion associates only with the provided metadata (e.g., index 5 with 'Amex Credit Card').

Kameleoon.API.Data.setCustomData(5, 'Credit Card');
Kameleoon.API.Data.setCustomData(9, 'Express Delivery');

Kameleoon.API.Goals.processConversion("GoalIDorName", revenue, {
5: ["Amex Credit Card", "PayPal"], // PaymentMode Custom Data
4: 1234567, // OrderID CustomData
3: "1q2w3e4r" // PayPalID CustomData
})

triggerGoal (Custom Code for Custom Goal)

Inject custom code to trigger Custom Goals by creating a new goal and adding the code to the Trigger my goal panel.

triggerGoal triggers the goal from within the code panel without requiring a goal ID.

//No params
triggerGoal();
//With revenue
triggerGoal(49.99);
//With revenue and metadata
triggerGoal(49.99, {5: "Gold"});
Arguments
NameTypeDescription
revenueNumberTransaction amount. Providing this value enables Kameleoon to track purchase metrics, such as revenue and average cart amount. This field is optional.
metadataObjectSets specific values for custom data defined as goal metadata in the Kameleoon App. This field is optional.
note

Metadata values are accessible through raw data exports and the results page.

If providing the metadata parameter, Kameleoon uses these specified values for the current conversion instead of the values previously collected via setCustomData(). If the parameter is omitted, Kameleoon uses the last tracked values for the customData prior to the conversion within the same visit.

Kameleoon considers only the metadata values passed directly to the triggerGoal() method and ignores previously set Custom Data. In the following example, the conversion associates only with the provided metadata (e.g., index 5 with 'Amex Credit Card').

Kameleoon.API.Data.setCustomData(5, 'Credit Card');
Kameleoon.API.Data.setCustomData(9, 'Express Delivery');

triggerGoal( revenue, {
5: ["Amex Credit Card", "PayPal"], // PaymentMode Custom Data
4: 1234567 // OrderID CustomData,
3: "1q2w3e4r" // PayPalID CustomData
})

Kameleoon.API.Data

This module provides methods for setting custom data to track customer or visit characteristics. It also includes data management methods for retrieving and writing data in Kameleoon's unified LocalStorage.

readLocalData

var userId = Kameleoon.API.Data.readLocalData("myUserId");

if (userId) {
Kameleoon.API.Data.retrieveDataFromRemoteSource(userId, function (data) {
console.log(data.returningVisitor);
});
}

The readLocalData() method reads local data previously stored via writeLocalData(). The engine retrieves this data from unified Local Storage, which bypasses standard storage limitations.

Arguments
NameTypeDescription
keyStringKey of the data to retrieve. This field is mandatory.
Return value
NameTypeDescription
valueStringValue of the data.

performRemoteSynchronization

Kameleoon.API.Data.performRemoteSynchronization("customDataName", "customDataValue", false);

The performRemoteSynchronization() method triggers a Server Synchronization Call (SSC) to the Data API. This call retrieves visit history stored on Kameleoon backend servers for the current visitor and writes it to LocalStorage. This ensures data accessibility via the Activation API and availability for targeting. This method typically runs automatically for cross-device reconciliation or Safari ITP and does not require manual invocation.

Arguments
NameTypeDescription
keyStringKey of the custom data serving as the mapping identifier (e.g., account ID or email). If omitted, the method uses the default identifier configured for cross-device reconciliation in the Kameleoon App.
valueStringCurrent visitor identifier value used for the Data API call. If omitted, the method uses the current value of the custom data provided in the first argument.
currentVisitOnlyBooleanWhen active, the SSC requests data only for the current visit. Use this optimization to refresh custom data values acquired via the Data API or Server-to-Server integration. If omitted, the method defaults to false.

resetCustomData

Kameleoon.API.Data.resetCustomData("MyCustomDataName");

The resetCustomData() method resets a custom data value.

Arguments
NameTypeDescription
nameStringName of the custom data as defined in the Kameleoon App. This field is mandatory.

retrieveDataFromRemoteSource

if (location.href.indexOf("loginPage") != -1) {
Kameleoon.API.Core.runWhenConditionTrue(function () {
return typeof dataLayer != null;
}, function () {
dataLayer.forEach(function (map) {
if (map.userId) {
Kameleoon.API.Data.retrieveDataFromRemoteSource(userId, function (data) {
Kameleoon.API.Data.setCustomData("known_user", data.knownUser);
});
}
});
}, 200);
}

The retrieveDataFromRemoteSource() method retrieves data stored on a remote Kameleoon server using the specified key. This method supports retrieving data previously stored via the Data API. Use this for quick storage and retrieval of large data volumes for visitors.

This asynchronous mechanism requires a callback function for server call completion.

Arguments
NameTypeDescription
keyStringThe lookup key. This field is mandatory.
callbackFunctionFunction called when data has been retrieved. It is called with a *data argument that is a JS Object. This field is mandatory.

setCustomData


// Single Type Custom Data
Kameleoon.API.Data.setCustomData("mySingleCustomDataName", "myNewValue"); --> "myNewValue"

// List Type Custom Data
Kameleoon.API.Data.setCustomData("myListCustomDataName", "myFirstValue"); --> ["myFirstValue"]
Kameleoon.API.Data.setCustomData("myListCustomDataName", "mySecondValue"); --> ["myFirstValue", "mySecondValue"]
Kameleoon.API.Data.setCustomData("myListCustomDataName", ["myThirdValue", "myFourthValue"]); --> ["myFirstValue", "mySecondValue", "myThirdValue", "myFourthValue"]
Kameleoon.API.Data.setCustomData("myListCustomDataName", ["myThirdValue", "myFourthValue"], true); --> ["myThirdValue", "myFourthValue"]

// Count List Type Custom Data
Kameleoon.API.Data.setCustomData("myCountListCustomDataName", "myFirstValue"); --> {value: 'myFirstValue', count: 1}
Kameleoon.API.Data.setCustomData("myCountListCustomDataName", "myFirstValue"); --> {value: 'myFirstValue', count: 2}
Kameleoon.API.Data.setCustomData("myCountListCustomDataName", "mySecondValue"); --> --> {value: 'myFirstValue', count: 2}, {value: 'mySecondValue', count: 1}

The setCustomData() method sets a custom data value.

Arguments
NameTypeDescription
CustomDataNameOrIndexString or NumberName or Index of the custom data as defined in the Kameleoon App. (the index appears in the 'INDEX' column of the Custom Data dashboard). This field is mandatory.
valueString, Number, Boolean, ArrayValue of the custom data. The argument provided should match the type declared for this custom data in the Kameleoon app. This field is mandatory. Please be aware that setCustomData() accepts String, Number, and Boolean when the Type is set to Single. If the Type is set to List or Count List, it will accept an array of String or Number.
overwriteBooleanOptional boolean. When true, the new value overwrites existing custom data. When false or omitted: Lists/Count Lists append values (all values appear in reports); Single types overwrite (only the latest value appears); Page-scoped Custom Data (all types) append values.

writeLocalData

Kameleoon.API.Data.writeLocalData("myData", "myDataValue", true);

The writeLocalData() method records local data in the visitor's browser for later retrieval via readLocalData(). The engine stores this as unified session data in Local Storage, bypassing standard storage limitations. Data becomes available immediately for retrieval in the same tab via RAM caching, while the physical write occurs asynchronously.

Arguments
NameTypeDescription
keyStringKey (name) of the data to write. This field is mandatory.
valueStringValue of the data to write. This field is mandatory.
persistentBooleanToggle data persistence. Non-persistent data expires after 1 hour, while persistent data remains for 30 days. If omitted, the method defaults to false.

Kameleoon.API.Events

This module triggers custom events for experiment and personalization targeting. Review the Activation API events documentation for standard DOM events.

trigger

Kameleoon.API.Events.trigger("myTriggerEventName");

The trigger() method triggers a custom event used in targeting segments.

Arguments
NameTypeDescription
eventNameStringName of the event to trigger. This field is mandatory.

Kameleoon.API.Tracking

This module integrates Kameleoon results with third-party tracking and analytics platforms, such as Adobe Analytics (Omniture).

processOmniture

function s_doPlugins(s) {
/* Kameleoon Integration */
window.kameleoonQueue = window.kameleoonQueue || [];
kameleoonQueue.push(['Tracking.processOmniture', s]);
window.kameleoonOmnitureCallSent = true;

// Add your other doPlugins code below
}

s.doPlugins = s_doPlugins;

Kameleoon provides a native integration with Adobe Analytics (Omniture). Follow the example to modify the file containing the s_doPlugins() code. Complete the following steps within the function:

  • Add a call to Kameleoon.API.Tracking.processOmniture().
  • Set the window.kameleoonOmnitureCallSent global variable to true to track initial call transmission. While this variable can be set elsewhere, setting it within s_doPlugins() is recommended.

The integration minimizes the number of Adobe Analytics hits to manage costs. Kameleoon sends an additional hit only if an experiment or personalization triggers after the main tracking call. This results from asynchronous loading (where Kameleoon loads after the analytics code) or "late" triggers, such as those occurring after page load (e.g., button clicks).

When Kameleoon loads first and identifies active experiments at page load, the global tracking call includes all additional data.

Arguments
NameTypeDescription
omnitureObjectObjectReference to your Omniture object. Usually, the global "s" variable (window.s) represents the Omniture object. It is also passed as an argument (named "s" as well) to the s_doPlugins() method. This field is mandatory.

Kameleoon.API.Products

This module provides access to the product catalog. Use it to register product views or purchases, add products to a cart, retrieve recommendations, or obtain product statistics (e.g., hourly or daily view and purchase counts).

note

This module is available when subscribed to the Product Recommendation module or Product Targeting add-on.

obtainRecommendedProducts

Kameleoon.API.Products.obtainRecommendedProducts(
"1a2b3c4d",
{
item: 123500,
exclude: [3, 14, 159, 26535],
category: 146,
search_query: "To be or not to be",
limit: 15,
brands: ["Alas", "poor", "Yorick", 'kameleooner'],
categories: [1, 146, 123500]
},
function (response) {
// the functionality of rendering a block of product recommendations
},
function (error) {
// when something went wrong
}
);

The obtainRecommendedProducts() method retrieves recommended products computed by the specified algorithm via an asynchronous server call.

caution

This method requires correct product tracking (via trackProductView(), trackCategoryView(), etc.) to return meaningful results.

Arguments
NameTypeDescription
codeStringUnique code of the recommendation block.
paramsObjectParameters to control the data returned by the recommendation platform.
successCallbackFunctionCallback function receiving the API response object. This field is mandatory.
errorCallbackFunctionCallback function executing if an error occurs. This field is optional.

Parameters to control the data returned by the recommendation platform

NameTypeDescription
itemStringID of the current product. Mandatory for "Similar" and "They also bought this product" algorithms.
excludeArrayComma-separated list of product identifiers for exclusion.
extendedNumberWhen "1", the method returns full product details. If omitted, it returns only product IDs.
categoryNumberMandatory for algorithms on category pages. Limits recommendations to the specified category.
categoriesArrayThis field is optional. If used, it returns recommended products only from the specified categories (a comma-separated list of category IDs).
brandsArrayThis field is optional. If used, it returns recommended products only from specified brands (a comma-separated list of brands).
locationsArrayThis field is optional. If used, it returns recommended products available in the listed locations (a comma-separated list of location IDs).
limitNumberThis field is optional. Maximum number of recommended products.
exclude_brandsNumberThis field is optional. A comma-separated list of brands that must be excluded from the recommendation.

API response

The callback function receives the API response object with the following values.

NameTypeDescription
htmlStringThe block HTML code. Customize the HTML template in the Kameleoon personal account.
titleStringThe block title. Corresponds to the value of the "Action" element in the block rules.
productsArrayA list of product IDs.
idNumberUnique block identifier. Corresponds to the block ID in the list of blocks in the Kameleoon personal account

trackAddToCart

var buyButton = Kameleoon.API.Utils.querySelectorAll("#buyButton")[0];
Kameleoon.API.Utils.addEventListener(buyButton, "mousedown", function () {
Kameleoon.API.Products.trackAddToCart("myProductId", 19.99, 1, {
stock: true,
recommended_code: 'some-unique-code' //see the arguments table for more information
recommended_by: 'dynamic'//see the arguments table for more information
});
});

The trackAddToCart() method triggers when a visitor adds a product to the shopping cart.

Arguments
NameTypeDescription
productIDStringUnique product identifier. This field is mandatory.
unitPriceNumberPrice for a single unit of the product referenced by productID. This field is optional; if not specified, the default price of the product from the imported product feed will be used.
amountNumberTotal quantity of the product after the cart update. Use non-incremental values. For example, if the cart contains two items of the same productID and another is added, specify 3. If removing two items from a cart containing 20, specify 18.
parametersObjectParameters for the recommendation platform. This field is optional.

Parameters for the recommendation platform

NameTypeDescription
recommended_byStringFor SPAs or pop-ups, set this value to "dynamic". This field is mandatory in specific scenarios.
recommended_codeStringFor SPAs or pop-ups, provide the unique widget code found in the "data-recommender-code" attribute in the account.
stockBooleanProduct availability. This value overrides data from product feeds or catalog imports. This field is optional.

trackAddToWishList

Kameleoon.API.Products.trackAddToWishList("myProductId"); // to add to wish list

Kameleoon.API.Products.trackAddToWishList("myProductId", -1); // to remove from wish list

The trackAddToWishList() method executes when a visitor adds or removes a product from the wish list or favorites.

NameTypeDescription
productIdStringUnique identifier of the product added to the wishlist. This field is mandatory.
quantityNumberQuantity to update. Use negative values (e.g., -1) to indicate removal. If omitted, the method defaults to 1.

trackCategoryView

if (location.href.indexOf("productPage") != -1) {
Kameleoon.API.Core.runWhenConditionTrue(function () {
return typeof dataLayer != null;
}, function () {
dataLayer.forEach(function (map) {
if (map.categoryID) {
Kameleoon.API.Products.trackCategoryView(5);
}
});
}, 200);
}

The trackCategoryView() method executes for each category page view during a session.

Arguments
NameTypeDescription
categoryIDStringUnique category identifier. This field is mandatory.

trackProductView

Kameleoon.API.Products.trackProductView("myProductID", {
"name": "productName",
"categories": [{
"id": "13",
"name": "productCategory",
"parent": null,
"url": "website.com/category/2"
}],
"imageURL": "https://www.mywebsite/productImage.jpg",
"price": 19.99,
"oldPrice": 23.99,
"accessories": ['productID1', 'productID2'],
"available": true,
"availableQuantity": 15,
"brand": "productBrand",
"groupId": "groupID1",
"sku": "productSKU",
"description": "This is a short description",
"rating": 4,
"model": "phone 14 128GB",
"leftovers": "one",
"tags": ["shirt", "red"],
"typePrefix": "mobile phone",
"seasonality": [1, 2, 3, 10, 11, 12],
"priceMargin": 100,
"isChild": false,
"isNew": false,
"isFashion": true,
"auto": {
"vds": ["BP8AN5", "HH5820"],
"compatibility": [
{
"brand": "BMW"
},
{
"brand": "Mini", "model": "Cooper S"
}
]
},
"fashion": {
"gender": "f",
"type": "shoe",
"sizes": ["37", "42"],
"feature": "adult",
"colors": [
{
"color": "red"
},
{
"color": "green", "picture": "https://example.com/items/395532-green.jpg"
}
]
},
"params": [
{
"name": "connectivity",
"value": ["bluetooth", "wi-fi"]
},
{
"name": "lengths",
"value": ["4", "6", "8"],
"unit": "cm"
}
]
});

The trackProductView() method executes for each product view during a session. This method allows Kameleoon to build an automated product catalog without requiring XML feed integration, simplifying the setup of product recommendation projects.

Arguments
NameTypeDescription
productIDStringProduct identifier. This can be any unique identifier for this particular product. This field is mandatory.
productDataObjectProduct object. This field is mandatory for importing product feeds via the Product Recommendation add-on.

trackSearchQuery

Kameleoon.API.Products.trackSearchQuery("Example search request");

The trackSearchQuery() method records user search queries.

Arguments
NameTypeDescription
search_queryStringThe search query value. This field is mandatory.

trackTransaction

Kameleoon.API.Products.trackTransaction(
[
{
"productID": "myProductID1",
"quantity": 4
},
{
"productID": "myProductID4564",
"quantity": 1
}
],
{
"order": "N318",
"order_price": 29999
}
);

The trackTransaction() method executes when a transaction or purchase occurs.

Arguments
NameTypeDescription
productsArrayList of objects containing the productID and quantity for each product in the transaction. This field is mandatory.
paramsObjectAdditional parameters for the recommendation platform. This field is optional.
Additional parameters for trackTransaction
NameTypeDescription
orderstringStore order number. If omitted, the engine uses an internal numbering system, which prevents order status synchronization. Refer to the parameter descriptions below.
order_priceNumberFinal order cost, including discounts, bonuses, and additional services. If omitted, the engine calculates the cost from the product database without discounts or services.
emailstringCustomer email.
phonestringCustomer phone number.
promocodestringTransaction promo code.
order_cashnumberCash payment amount.
order_bonusesnumberBonus payment amount.
order_deliverynumberDelivery fee.
order_discountnumberOrder discount amount.
delivery_typestringDelivery method.
payment_typestringPayment type (e.g., "cash", "card", "wire").
tax_freebooleanTax-free status.

obtainInstantSearchProducts

Kameleoon.API.Products.obtainInstantSearchProducts(
{
search_query: "To be or not to be"
},
function (response) {
// the functionality to render a block from instant search
},
function (error) {
// to handle when something goes wrong
}
);

The obtainInstantSearchProducts() method retrieves personalized instant search results from Kameleoon Search via an asynchronous server call.

Arguments
NameTypeDescription
search_queryStringUser-provided search query. This field is mandatory.
successCallbackFunctionCallback function receiving the API response object. This field is mandatory.
errorCallbackFunctionCallback function executing if an error occurs. This field is optional.

API response

The callback function receives the API response object with the following values.

NameTypeDescription
search_queryStringSearch query
categoriesArrayArray with information about categories. Each object has the following properties:
  • id – category id (string)
  • name – category name (string)
  • url – category url (string)
  • count – count of products in category (number)
filtersArrayArray with information about filters. Each object has the following properties:
  • filter – filter object. Has the following properties:
  • count – total count of products whith this parameters (number)
  • values – array of values (object). Has the following properties:
  • value – value label. (string)
  • count – cont of products whith this parameter (number)
htmlStringHTML-code of the block with products. The template is customized in the Kameleoon personal account.
price_rangeObjectMin and max price of products. Has the following properties:
  • min – min price (number)
  • max – max price (number)
productsArrayArray with information about products. Each object has the following properties:
  • description – product description (string)
  • url – absolute product URL (string)
  • url_handle – relative product URL (string)
  • picture – product's picture URL in the Kameleoon storage (string)
  • name – product name (string)
  • price – product price (number / int)
  • price_full – product price (number / float)
  • price_formatted – product price with currency (string)
  • price_full_formatted – product price with currency (string)
  • image_url - absolute product's picture URL in the Kameleoon storage (string)
  • image_url_handle - relative product's picture URL in the Kameleoon storage (string)
  • image_url_resized - product image resizes url (array)
  • currency – product currency (string, corresponds to the currency of the personal account in Kameleoon, or a custom value specified in the shop settings in the personal account)
  • id – product ID (string)
  • old_price – product old price (number / int, default - 0)
  • old_price_full – product old price (number / float)
  • old_price_formatted – product old price with currency (string)
  • old_price_full_formatted – product old price with currency (string)
  • Additional properties. If a parameter "extended" is passed in the request categories – product categories (array). Has the following properties:
    • id – category id (string)
    • name – category name (string)
    • parent_id – parent category id (string)
    • url - category url
    • category_ids - product categories ids (array).
search_query_redirectsarrayArray with information about redirects. Each object has the following properties:
  • query – search query (string)
  • redirect_link – Url for redirect (string)
  • deep_link – Url for mobile apps (string)
products_totaNumberTotal number of products

obtainFullSearchProducts

Kameleoon.API.Products.obtainFullSearchProducts(
{
search_query: "To be or not to be",
limit: 15,
brands: ["Alas", "poor", "Yorick"],
categories: [1, 146, 100500],
filters: { key: ["value"], key: ["value"] },
sort_by: "price",
order: "asc"
},
function (response) {
// the functionality to render a block from full search
},
function (error) {
// when something went wrong
}
);

Use the obtainFullSearchProducts() method to retrieve full search results from the Kameleoon Search solution with filtering options.

Arguments
NameTypeDescription
search_queryObjectUser-provided search query and optional filter parameters. Review the filtering parameters in the next section. This field is mandatory.
successCallbackFunctionCallback function receiving the API response object. This field is mandatory.
errorCallbackFunctionCallback function executing if an error occurs. This field is optional.
Parameters to filter results
NameTypeDescription
search_queryStringSearch query. This field is mandatory.
limitNumberLimit of results. This field is optional.
offsetNumberOffset of results. This field is optional.
category_limitNumberHow many categories for sidebar filter to return. This field is optional.
categoriesArrayComma separated list of categories to filter. This field is optional.
extendedNumberSet to true for full search results.
sort_byStringSort by parameter: popular, price, discount, sales_rate, date. This field is optional.
orderStringSort direction: asc or desc (default). This field is optional.
locationsArrayComma separated list of locations IDs. This field is optional.
brandsArrayComma separated list of brands to filter. This field is optional.
filtersStringOptional escaped JSON string with filter parameters. For example: {"bluetooth":["yes"],"offers":["15% cashback"],"weight":["1.6"]}. This field is optional.
price_minNumberMin price. This field is optional.
price_maxNumberMax price. This field is optional.
colors falseArrayComma separated list of colors. This field is optional.
fashion_sizesArrayComma separated list of sizes. This field is optional.
excludeArrayComma separated list of products IDs to exclude from search results. This field is optional.
emailStringIt's only for S2S integration, when service doesn't have user's session. Mobile SDK doesn't use it. This field is optional.
no_clarificationBooleanDisables clarified search. Defaults to false. Do not use this parameter unless instructed by Kameleoon support.
merchantsArrayComma separated list of merchants. This field is optional.
filters_search_byStringAvailable options for filter: name, quantity, popularity. This field is optional.

API response

The callback function receives the API response object with the following values.

NameTypeDescription
brandsArrayArray with information about brands. Each object has the following properties:
  • name – brand name (string)
  • picture – brand picture (string)
categoriesArrayArray with information about categories. Each object has the following properties:
  • alias – category alias (string)
  • id – category id (string)
  • name – category name (string)
  • parent – parent category id (string)
  • url – category url (string)
filtersArrayArray with information about filters. Each object has the following properties:
  • filter – filter object. Has the following properties:
    • count – total count of products whith this parameters (number)
    • values – array of values (object). Has the following properties: * value – value label. (string), count – cont of products whith this parameter (number)
htmlStringHTML-code of the block with products. The template is customized in the Kameleoon personal account.
price_rangeObjectMin and max price of products. Has the following properties:
  • min – min price (number)
  • max – max price (number)
productsArrayArray with information about products. Each object has the following properties:
  • brand – product brand (string)
  • currency – product currency (string, corresponds to the currency of the personal account in Kameleoon, or a custom value specified in the shop settings in the personal account)
  • id – product ID (string)
  • is_new – product property (boolean, default - null)
  • name – product name (string)
  • old_price – product old price (string, default - 0)
  • picture – product's picture URL in the Kameleoon storage (string)
  • price – product price (number)
  • price_formatted – product price with currency (string)
  • url – product URL (string)
  • Additional properties if a parameter "extended" is passed in the request:
    • barcode – product barcode (string)
  • categories – product categories (array). Has the following properties:
    • id – category id (string)
    • name – category name (string)
    • parent – parent category id (string)
  • params – array with information about params. Each object has the following properties:
    • key – param name (string)
    • values – array of values (array)
products_totalNumberTotal count of products
search_queryStringSearch query typed by the user.

obtainProductInteractions

Kameleoon.API.Products.obtainProductInteractions("123456", product => {
console.log("product", product); // {123456: {views: 1, cartQuantities: 0, boughtQuantities: 0}}
});
Kameleoon.API.Products.obtainProductInteractions(["123456", "654321"], products => {
console.log("products", products);
});
Kameleoon.API.Products.obtainProductInteractions(
"123456",
callback,
new Date().getTime() - 1000 * 60 * 60 * 24, // timeBegin
new Date().getTime() // timeEnd
);

The obtainProductInteractions() method retrieves interaction metrics for products tracked via trackProductView(), trackTransaction(), or trackAddToCart().

Arguments
NameTypeDescription
eansArrayProduct IDs (as Strings). This field is mandatory.
callbackFunctionCallback function receiving the product data. This field is mandatory.
timeBeginNumberStart of the date range (UNIX milliseconds timestamp).
timeEndNumberEnd of the date range (UNIX milliseconds timestamp).
API Response
NameTypeDescription
eansArrayUnique identifier of the product. Each product ID maps to an object containing interaction metrics.
viewsintegerNumber of times the product has been viewed.
cartQuantitiesintegerTotal number of times the product has been added to visitors’ carts.
boughtQuantitiesintegerTotal number of times the product has been purchased.

obtainProductData

Kameleoon.API.Products.obtainProductData("123456", product => {
console.log("product", product);
});
Kameleoon.API.Products.obtainProductData(["123456", "654321"], products => {
console.log("products", products);
});
Kameleoon.API.Products.obtainProductData("123456", callback, {
name: true,
categoryId: true
}); // {123456: {name: '', categoryId: '' }}

The obtainProductData() method retrieves product information for items sent via trackProductView().

Arguments
NameTypeDescription
eansArrayProduct IDs (as Strings). This field is mandatory.
callbackFunctionCallback function receiving the product data. This field is mandatory.
parametersObjectOptional parameters to retrieve specific fields. Defaults to { all: true }.
API Response
NameTypeDescription
eansArrayUnique identifier of the product. Each product ID maps to an object containing interaction metrics.
productDataObjectProduct object. The same object sent by trackProductView will be recieved in this field.

obtainRecommendedCollections

Kameleoon.API.Products.obtainRecommendedCollections("123456", collections => {
/* The functionality of rendering a product collection block */
console.log("collections", collections);
}, error => {
/* Error handling logic if something goes wrong */
});

The obtainRecommendedCollections() method retrieves products from the specified collection.

Arguments
NameTypeDescription
collectionIdStringProduct collection ID, available in the Product Collections dashboard section.
successCallbackFunctionCallback function receiving the API response object. This field is mandatory.
errorCallbackFunctionCallback function executing if an error occurs. This field is optional.

API response

Products

API returns an array of objects. Each object in the products array contains the following:

ParameterTypeDescription
nameStringName of the product
urlString (URL)URL of the product page
descriptionStringDescription of the product
category_idsArray of StringsList of category IDs the product belongs to
brandStringBrand of the product
fashion_featureStringFashion feature (e.g., "adult")
fashion_genderStringIntended gender for the product
sales_rateIntegerProduct's sales rate
relative_sales_rateFloatSales rate relative to other products
pictureString (URL)URL of the main product image
categoriesArray of ObjectsList of category objects (system-defined structure)
price_formattedStringFormatted product price (e.g., $29.99)
price_full_formattedStringFormatted full/original price
priceFloatCurrent product price
price_fullFloatOriginal/full price before any discounts
image_urlString (URL)URL of the resized product image
image_url_handleString (URL)Processed image URL (handle-based)
image_url_resizedString (URL)Resized image URL
url_handleStringURL handle used to access the product within the collection
currencyStringCurrency code used for the product price (e.g., USD, EUR)
idStringProduct ID (numeric or string depending on system)
htmlString (HTML)The HTML template selected when the collection was created

Kameleoon.API.Experiments

This module provides methods for accessing live experiments.

note

This module is only available with Kameleoon Web Experimentation solution.

assignVariation

var experimentID = 2468;
var variationID;

if (Kameleoon.API.CurrentVisit.device.type == "Desktop") {
variationID = 123456;
} else if (Kameleoon.API.CurrentVisit.device.type == "Tablet") {
variationID = 654321;
} else {
variationID = 987654;
}

Kameleoon.API.Experiments.assignVariation(experimentID, variationID);

The assignVariation() method forces the association of a specific variation for an experiment, overriding the standard allocation algorithm. If called before the experiment triggers, the engine pre-allocates the variation for later activation. When the experiment has already triggered, set the override argument to true to replace the existing association.

Arguments
NameTypeDescription
experimentIDNumberID of the experiment. This field is mandatory.
variationIDNumberID of the variation. This field is mandatory.
overrideBooleanWhen true, the engine replaces any existing variation association with the provided value. If omitted, the method defaults to false.

block

// The experiment will be blocked for the current page
Kameleoon.API.Experiments.block(12345);

// The experiment will be blocked for the whole visit
Kameleoon.API.Experiments.block(54321, true);

The block() method prevents experiment triggering or activation, including manual calls via trigger(). The block applies to the current page by default (until the next Kameleoon.API.Core.load()). Set the visit argument to true to block the experiment for the entire visit.

Arguments
NameTypeDescription
experimentIDNumberID of the experiment. This field is mandatory.
visitBooleanWhen true, the engine blocks the experiment for the entire visit. If omitted, the block applies only to the current page (default: false).

getAll

Kameleoon.API.Experiments.getAll().forEach(function (experiment) {
if (experiment.id == 123456 && experiment.active) {
console.log(experiment.name);
}
});

The getAll() method returns all live experiments (running, not draft/paused/stopped).

Return value
NameTypeDescription
experimentsArrayList of Experiment objects.

getActive

if (Kameleoon.API.Experiments.getActive().length == 0) {
Kameleoon.API.Events.trigger("No Experiments Events");
}

The getActive() method returns active experiments for the current visit and page. An experiment is active if its variation code has executed in the current session context. To retrieve experiments activated on other URLs during the visit, use getActivatedInVisit().

Return value
NameTypeDescription
experimentsArrayList of Experiment objects.

getById

var experiment = Kameleoon.API.Experiments.getById(123456);

if (experiment && experiment.active) {
console.log(experiment.name);
}

The getById() method returns the experiment for the specified ID.

Arguments
NameTypeDescription
idNumberID of the experiment. This field is mandatory.
Return value
NameTypeDescription
experimentObjectExperiment object.

getByName

var experiment = Kameleoon.API.Experiments.getByName("MyExperimentName");

if (experiment && experiment.active) {
console.log(experiment.id);
}

The getByName() method returns the experiment for the specified name.

Arguments
NameTypeDescription
nameStringName of the experiment. This field is mandatory.
Return value
NameTypeDescription
experimentObjectExperiment objects.

getTriggeredInVisit

Kameleoon.API.Experiments.getTriggeredInVisit().forEach(function (experiment) {
if (experiment.id == 123456) {
console.log(experiment.name);
}
});

The getTriggeredInVisit() method returns all experiments triggered during the current visit.

Return value
NameTypeDescription
experimentsArrayList of Experiment objects.

getActivatedInVisit

Kameleoon.API.Experiments.getActivatedInVisit().forEach(function (experiment) {
if (experiment.id == 123456) {
console.log(experiment.name);
}
});

The getActivatedInVisit() method returns all experiments activated during the current visit.

Return value
NameTypeDescription
experimentsArrayList of Experiment objects.

trigger

let experimentID = 123456;
Kameleoon.API.Experiments.trigger(experimentID, true);

The trigger() method forces an experiment trigger, bypassing targeting segment conditions. This action initiates the experiment but may not activate it.

Arguments
NameTypeDescription
experimentIDNumberID of the experiment. This field is mandatory.
trackingOnlyBooleanSet to true for hybrid experiments (backend implementation with frontend tracking) to perform only tracking actions without executing variation assets (JS, CSS, redirections). If omitted, the method defaults to false.

Kameleoon.API.Personalizations

This module provides methods for accessing live personalizations.

disable

let personalizationID = 12345;
Kameleoon.API.Personalizations.disable(personalizationID);

The disable() method marks a personalization as disabled. Use this for interactive elements like pop-ins; when a user closes the element, call disable() to update the personalization status. Kameleoon automatically implements this call for native (non-custom) interface elements.

Arguments
NameTypeDescription
idNumberId of the personalization. This field is mandatory.

getActive

if (Kameleoon.API.Personalizations.getActive().length == 0) {
Kameleoon.API.Events.trigger("No Personalizations Events");
}

The getActive() method returns active personalizations for the current visit and page. A personalization is active if its variation code has executed and the associated action remains visible. To retrieve personalizations triggered on other URLs or since closed (e.g., pop-ins), use getTriggeredInVisit().

Return value
NameTypeDescription
personalizationsArrayList of Personalization objects.

getAll

Kameleoon.API.Personalizations.getAll().forEach(function (personalization) {
if (personalization.id == 123456 && personalization.active) {
console.log(personalization.name);
}
});

The getAll() method returns all live personalizations (running, not draft/paused/stopped).

Return value
NameTypeDescription
personalizationsArrayList of Personalization objects.

getById

var personalization = Kameleoon.API.Personalizations.getById(123456);

if (personalization && personalization.active) {
console.log(personalization.name);
}

The getById() method returns the personalization for the specified ID.

Arguments
NameTypeDescription
idNumberId of the personalization. This field is mandatory.
Return value
NameTypeDescription
personalizationObjectPersonalization object.

getByName

var personalization = Kameleoon.API.Personalizations.getByName("MyPersonalizationName");

if (personalization && personalization.active) {
console.log(personalization.id);
}

The getByName() method returns the personalization for the specified name.

Arguments
NameTypeDescription
nameStringName of the personalization. This field is mandatory.
Return value
NameTypeDescription
personalizationObjectPersonalization object.

getTriggeredInVisit

Kameleoon.API.Personalizations.getTriggeredInVisit().forEach(function (personalization) {
if (personalization.id == 123456) {
console.log(personalization.name);
}
});

The getTriggeredInVisit() method returns all personalizations triggered during the current visit.

Return value
NameTypeDescription
personalizationsArrayList of Personalization object.

getActivatedInVisit

Kameleoon.API.Personalizations.getActivatedInVisit().forEach(function (personalization) {
if (personalization.id == 123456) {
console.log(personalization.name);
}
});

The getActivatedInVisit() method returns all personalizations activated during the current visit.

Return value
NameTypeDescription
personalizationsArrayList of Personalization object.

trigger

let personalizationID = 123456;
Kameleoon.API.Personalizations.trigger(personalizationID, true);

The trigger() method forces a personalization trigger, bypassing targeting segment conditions. This action initiates the personalization but may not activate it.

Arguments
NameTypeDescription
personalizationIDNumberID of the personalization. This field is mandatory.
trackingOnlyBooleanSet to true for external personalizations (targeting or tracking managed by Kameleoon) to perform only tracking actions without executing variation assets (JS, CSS, redirections). If omitted, the method defaults to false.

Kameleoon.API.Variations

This module provides methods for managing variations.

execute

if (Kameleoon.API.Utils.querySelectorAll("#KameleoonPopin").length == 0) {
Kameleoon.API.Experiments.getById(123456).variations.forEach(function (variation) {
if (variation.name == "MyVariation") {
Kameleoon.API.Variations.execute(variation.id);
}
});
}

The execute() method executes JavaScript and applies CSS for the specified variation ID.

Kameleoon.API.Segments

This module provides methods for managing segments and targeting.

getAll

let segments = Kameleoon.API.Segments.getAll();

The getAll() method returns all live segments, including those associated with experiments, personalizations, or Audience tracking.

Return value
NameTypeDescription
segmentsArrayList of Segment objects.

getById

let segment = Kameleoon.API.Segments.getById(123456);

The getById() method returns the segment for the specified ID.

Arguments
NameTypeDescription
idNumberId of the segment. This field is mandatory.
Return value
NameTypeDescription
segmentObjectSegment object.

getByName

let segment = Kameleoon.API.Segments.getByName("My segment");

The getByName() method returns the segment for the specified name.

Arguments
NameTypeDescription
nameStringName of the segment. This field is mandatory.
Return value
NameTypeDescription
segmentObjectSegment object.

reevaluate

Kameleoon.API.Utils.addEventListener(document.body, "mouseleave", function (event) {
if (event.clientY < 0) {
Kameleoon.API.Segments.reevaluate(123456);
}
});

The reevaluate() method forces an immediate re-evaluation of the targeting conditions for the specified segment. Evaluation typically occurs at page load, resulting in statuses of true, false, or undefined. This method restarts the evaluation process as if the engine had just initialized.

Arguments
NameTypeDescription
idNumberId of the segment. This field is mandatory.

trigger

Kameleoon.API.Segments.trigger(12345);

The trigger() method forces a segment trigger for the current visitor, bypassing targeting conditions.

Arguments
NameTypeDescription
idNumberId of the segment. This field is mandatory.

Kameleoon.API.Utils

This module provides utility methods for common operations.

addEventListener

var popin = document.createElement("div");
popin.id = "kameleoonPopin";
popin.innerHTML = "<img src='https://www.mywebsite.com/myImage.jpg'/>";
document.body.appendChild(popin);

Kameleoon.API.Utils.addEventListener(popin, "mousedown", function (event) {
document.body.removeChild(popin);
});

The addEventListener() method attaches an event handler to the specified element.

note

Kameleoon resets all event listeners created via this API during engine reloads. Use this method to add listeners in SPAs to ensure proper cleanup.

Arguments
NameTypeDescription
elementObjectTarget element for the listener. This field is mandatory.
eventTypeStringEvent name. This field is mandatory.
callbackFunctionFunction to execute when the event triggers. This field is mandatory.

addUniversalClickListener

let btn = document.querySelector("#MyButton");

Kameleoon.API.Utils.addUniversalClickListener(btn, function (event) {
let goalID = 1234;
Kameleoon.API.Goals.processConversion(goalID);
});

The addUniversalClickListener() method attaches a click handler that listens for mouse clicks on desktop and touchdown events on mobile devices and tablets. For mobile devices, a touchdown occurs if the engine detects a touchstart event followed by a touchend event without an intermediate touchmove.

note

Kameleoon resets all listeners created via this API during engine reloads, facilitating cleanup in SPAs.

note

On desktop devices, right-clicks trigger this method (e.g., when opening a link in a new tab).

Arguments
NameTypeDescription
elementObjectTarget element for the listener. This field is mandatory.
callbackFunctionFunction to execute when the click event triggers. This field is mandatory.

clearInterval

var myInterval = Kameleoon.API.Utils.setInterval(function () {
if (window.dataLayer != null) {
Kameleoon.API.Utils.clearInterval(myInterval);
}
}, 1000);

The clearInterval() method clears a timer set via setInterval().

Arguments
NameTypeDescription
intervalIdNumberTimer ID returned by the setInterval() method. This field is mandatory.

clearTimeout

var myTimeout = Kameleoon.API.Utils.setTimeout(function () {
var popin = document.createElement("div");
popin.id = "kameleoonPopin";
popin.innerHTML = "<img src='https://www.mywebsite.com/myImage.jpg'/>";
document.body.appendChild(popin);
}, 5000);

Kameleoon.API.Utils.addEventListener(document.body, "mousedown", function () {
Kameleoon.API.Utils.clearTimeout(myTimeout);
});

The clearTimeout() method clears a timer set via setTimeout().

Arguments
NameTypeDescription
timeoutIdNumberTimer ID returned by setTimeout().

computeHash

var emailId = Kameleoon.API.Utils.createHash("myemail@mail.com");
Kameleoon.API.Data.setCustomData("VisitorEmail", emailId);

The computeHash() method computes a hash from a string. Use this to process unique data without manipulating sensitive personal information directly.

Arguments
NameTypeDescription
stringStringThe source string from which to compute the hash.
Return value
NameTypeDescription
hashStringResulting hash. The algorithm used is the same as the implementation of hashCode() for java.lang.String.

getURLParameters

var parameters = Kameleoon.API.Utils.getURLParameters();

if (parameters.productID != null) {
Kameleoon.API.Events.trigger("ProductPage");
}

The getURLParameters() method parses the current URL and returns all detected parameters. This method supports both search (?) and hash (#) parameters.

Return value
NameTypeDescription
parametersObjectObject with parameter names as keys and parameter values as values.

performRequest

Kameleoon.API.Utils.performRequest(
"https://www.my_web_server_url.com",
function () {
if (this.readyState == 4 && this.status == 200) {
eval(this.responseText);
}
},
function() {
console.log("Request cancelled");
},
2000
);

The performRequest() method initiates a call to a remote web server.

Arguments
NameTypeDescription
urlStringThe URL of the remote server. This field is mandatory.
readyStateHandlerFunctionA callback function that will be executed when a reply is received from the server. The event argument is passed to this function (load event) and the underlying XMLHttpRequest object is bound to the callback. So all properties from XMLHttpRequest are available inside the callback via this. This field is optional.
errorHandlerFunctionA callback function that will be called in case an error occurs. The event argument is passed to this function (error event or timeout event) and the underlying XMLHttpRequest object is bound to the callback. So all properties from XMLHttpRequest are available inside the callback via this. This field is optional.
timeoutNumberWait time in milliseconds before cancelling the request. Defaults to 5000 milliseconds.

querySelectorAll

var foundElements = Kameleoon.API.Utils.querySelectorAll(".kameleoonClassName");

foundElements.forEach(function (element) {
element.style.display = "none";
});

The querySelectorAll() method returns all document elements matching the specified CSS selectors as a static NodeList object.

note

This method supports selectors with :contains and :eq.

Arguments
NameTypeDescription
selectorStringOne or more CSS selectors. This field is mandatory.
Return value
NameTypeDescription
elementsArrayList of elements matching the query.

setInterval

var countdown = 10;
var timer = document.createElement("div");
timer.innerHTML = countdown.toString();
document.body.appendChild(timer);

var myInterval = Kameleoon.API.Utils.setInterval(function () {
countdown--;
timer.innerHTML = countdown.toString();

if (countdown == 0) {
Kameleoon.API.Utils.clearInterval(myInterval);
}
}, 1000);

The setInterval() method executes a function or expression at the specified interval in milliseconds.

Kameleoon resets all intervals created via this API during engine reloads. Use this method in SPAs to ensure proper cleanup.

Arguments
NameTypeDescription
functionFunctionJavaScript function that will be executed periodically. This field is mandatory.
millisecondsNumberInterval duration in milliseconds. Defaults to 200 milliseconds.
Return value
NameTypeDescription
intervalIdNumberTimer ID for use with clearInterval().

setTimeout

var myTimeout = Kameleoon.API.Utils.setTimeout(function () {
Kameleoon.API.Events.Trigger("5 seconds elapsed");
}, 5000);

The setTimeout() method executes a function or expression after the specified number of milliseconds.

Kameleoon resets all timeouts created via this API during engine reloads. Use this method in SPAs to ensure proper cleanup.

Arguments
NameTypeDescription
functionFunctionJavaScript function that will be executed periodically. This field is mandatory.
millisecondsNumberWait time in milliseconds before executing the function. Defaults to 200 milliseconds.
Return value
NameTypeDescription
timeoutIdNumberTimer ID for use with clearTimeout().

Kameleoon.API.Visitor

This module provides a shortcut for obtaining a reference to the current Visitor object. The Activation API contains a single, unique Visitor object. This module also allows overriding the visitor code.

setVisitorCode

 // Setting up the Kameleoon VisitorCode Override

// Initialize the KameleoonQueue if it doesn't exist
window.kameleoonQueue = window.kameleoonQueue || [];

// Push the command to set the VisitorCode with your own ID

window.kameleoonQueue.push({
level: "IMMEDIATE",
command: () => Kameleoon.API.Visitor.setVisitorCode("<USER_ID>")
});

The setVisitorCode() method overrides the Kameleoon VisitorCode, which is a unique identifier randomly generated for every visitor. Ensure the provided ID is unique and does not exceed 255 characters.

Call this method as early as possible, specifically before Kameleoon triggers any experiments. Updating the VisitorCode after the engine assigns a variation causes a reassignment.

Kameleoon.API.CurrentVisit

This module provides a shortcut for obtaining a reference to the current (in-progress) Visit object. It references the same object as Kameleoon.API.Visitor.visits[Kameleoon.API.Visitor.visits.length - 1].

Configuration

A Configuration object holds global, constant values related to the current configuration of Kameleoon on this site.

Properties
NameTypeDescription
siteCodeStringThe unique site code corresponding to the Kameleoon application file installed on the website. It is a string of 10 random characters (lower case letters and numerals).
singlePageSupportBooleanSet to true if Single Page Support is configured. Configuration occurs globally via the Kameleoon app or via Kameleoon.API.Core.enableSinglePageSupport(). Single Page Support ensures URL changes trigger Kameleoon.API.Core.load() without requiring a browser page reload.
goalsArrayList of Goal objects representing all the active (configured) goals for this site.
generationTimeNumberTime of the last generation of the Kameleoon application file (UTC format - ms since 1st January, 1970).

Visitor

A Visitor object contains visitor-scoped data independent of specific visits. This object includes a list of all Visit objects for the visitor.

Properties
NameTypeDescription
codeStringThe randomly generated visitor code. Unless a custom value has been specifically set on the server (via a Kameleoon server-side SDK), it is a string of 16 random characters (lower case letters and numerals).
numberOfVisitsNumberTotal visits for the visitor. This value may exceed visits.length, as the Activation API retains only the latest 25 visits.
firstVisitStartDateNumberStart date (UNIX milliseconds) for the first visit. This value may not align with visits[0].startDate, as the Activation API retains only the latest 25 visits.
visitsArrayList of all the Visit objects made by this visitor on your website, with a maximum of 25 visits. If this visitor made more than 25 visits, only the latest 25 are available via this property.
currentVisitObjectVisit object corresponding to the current, in-progress visit. This is a reference to the same object as Kameleoon.API.CurrentVisit.
previousVisitObjectVisit object corresponding to the previous visit. If there was no previous visit (ie, the current visit is the first one), this property is null.
customDataObjectcustomData - Map of all the custom data with a scope of VISITOR. The keys of the map are the defined custom data names. Note that not all custom data are included on this map, only those that were defined in the Kameleoon app as having a scope of VISITOR. Other custom data can be accessed from a Visit object.
experimentLegalConsentBooleanBoolean equal to true if legal consent was obtained (or not required) for this visitor regarding the activation of experiments, else to false. This property can also be null while the visitor has not yet given his consent nor explicitely refused.
personalizationLegalConsentBooleanBoolean equal to true if legal consent was obtained (or not required) for this visitor regarding the activation of personalizations, else to false. This property can also be null while the visitor has not yet given his consent nor explicitely refused.

Visit

A Visit object represents a single visit and contains real-time information gathered by Kameleoon. Data points include visit context (device, location), observed behavior (duration, page views), and Kameleoon operations (triggered experiments or personalizations).

Properties
NameTypeDescription
indexNumberIndex of the visit. The first visit of a given visitor has an index of 0, the second of 1, etc. Note that only the 25 latest visits of a visitor can be accessed via the Activation API, so Kameleoon.API.Visitor.visits[0].index is not always equal to 0.
startDateNumberDate (UTC format - ms since 1st January, 1970) of the start of the visit.
durationNumberDuration of this visit in ms. If this visit is the current visit, this value is always up to date (it is recomputed each time it is accessed).
pageViewsNumberNumber of pages viewed during the visit. In SPAs, calling Kameleoon.API.Core.load() increments this number. URL changes automatically trigger this call if Single Page Support is enabled.
localeStringThe locale of the visitor's browser.
deviceObjectDevice object corresponding to the visitor's device for this visit.
geolocationObjectGeolocation object corresponding to the visitor's location for this visit.
weatherObjectWeather object corresponding to the visitor's weather for this visit.
activatedExperimentsArrayList of ExperimentActivation objects, corresponding to all the experiments that were activated on this visit.
activatedPersonalizationsArrayList of PersonalizationActivation objects, corresponding to all the personalizations that were activated on this visit.
conversionsObjectMap of conversions performed on this visit. The keys of the map are the defined goal IDs. The values are Objects with two keys: count (number of times this goal was converted for this visit) and revenue (total revenue of this goal for this visit).
customDataObjectMap of all the custom data with a scope of PAGE or VISIT. The keys of the map are the defined custom data names. Note that not all custom data are included on this map, only those that were defined on the Kameleoon app as having a scope of PAGE or VISIT. Other custom data can be accessed from the Visitor object.
currentProductObjectProduct object corresponding to the product displayed on the current product page. If the visitor is currently not on a product page, this property is null.
productsArrayList of Product objects, corresponding to all the product pages that were seen on this visit (including the currentProduct if applicable).
acquisitionChannelStringName of the acquisition channel for the visit. The list of acquisition channels, along with their characteristics (mainly how they can be inferred, for instance by URL parameter), are defined using the Kameleoon app.
landingPageURLStringURL of the first page of the visit, usually called the landing page.
initialConversionPredictionsObjectMap of Kameleoon Conversion Scores (KCS). The keys of the map are the defined key moment names. The values range from 0 to 100, representing the KCS for the designated key moment (Note: As of recently, key moment has been changed to triggers in the Kameleoon app).
note

The kameleoonConversionScores property is only available with the AI Predictive Targeting add-on.

Device

A Device object contains data about the device being used for a given visit.

Properties
NameTypeDescription
browserStringName of the browser. Possible values are: Chrome, Chromium, Firefox, Safari, Microsoft Edge, Internet Explorer, Opera, Android, iPhone, iPad, iPod, Samsung Internet for Android, Opera Coast, Yandex Browser, UC Browser, Maxthon, Epiphany, Puffin, Sleipnir, K-Meleon, Windows Phone, Vivaldi, Sailfish, SeaMonkey, Amazon Silk, PhantomJS, SlimerJS, BlackBerry, WebOS, Bada, Tizen, QupZilla, Googlebot, Blink, Gecko, Webkit.
browserVersionStringVersion of the browser.
osStringName of the OS. Possible values are: Windows, Mac, Linux, Android, iOS, Chrome OS, Windows Phone.
typeStringType of the device. Possible values are: Desktop, Tablet, Phone.
screenHeightNumberHeight of the device's screen (in pixels).
screenWidthStringWidth of the device's screen (in pixels).
windowHeightNumberHeight of the browser's window (in pixels).
windowWidthStringWidth of the browser's window (in pixels).
adBlockerBooleanBoolean equal to true if this device has an active ad blocker, else to false.
timeZoneStringTime zone of the browser. The value is a String (for instance "Europe/Paris") that corresponds to the TZ database of time zones.

Geolocation

A Geolocation object contains data about the physical location of the visitor for a given visit.

Properties
NameTypeDescription
countryStringCountry name, in English.
regionStringName of the region, in the country's preferred language.
cityStringName of the city, in the country's preferred language.
postalCodeStringPostal code.
latitudeNumberLatitude (in degrees).
longitudeNumberLongitude (in degrees).

Weather

A Weather object contains data about the weather conditions occuring at the time of the visit.

Properties
NameTypeDescription
temperatureStringTemperature in Kelvin.
humidityStringHumidity in percentage (from 0 to 100).
pressureStringAtmospheric pressure in hPa.
windSpeedStringWind speed in meters/sec.
cloudinessNumberCloudiness in percentage (from 0 to 100).
sunriseNumberTime of sunrise (UTC format - ms since 1st January, 1970).
sunsetNumberTime of sunset (UTC format - ms since 1st January, 1970).
conditionCodeNumberWeather condition ID code. Full reference list is available here.
conditionDescriptionStringWeather condition description. It is the description matching the conditionCode. For instance, a conditionCode of 800 would have a conditionDescription of clear sky.

Experiment

An Experiment object represents a Kameleoon A/B test. Core properties include the segment (trigger conditions) and associated variations. Variations contain the JavaScript and CSS code implementing the changes.

Properties
NameTypeDescription
idNumberID of the experiment.
nameStringName of the experiment.
dateLaunchedNumberTime of first launch of the experiment (UTC format - ms since 1st January, 1970).
dateModifiedNumberTime of last modification of the experiment (UTC format - ms since 1st January, 1970).
targetSegmentObjectSegment object associated with the experiment.
variationsArrayList of Variation objects for this experiment.
trafficDeviationObjectMap of current experiment traffic deviation. Keys are variation IDs (ID 0 is the reference). Values are percentages (0-100). The sum may not equal 100 if a portion of traffic is unallocated.
untrackedTrafficReallocationTimeNumberTime of the last reallocation performed for untracked traffic (UTC format - ms since 1st January, 1970). If a reallocation was never performed, the value will be null.
goalsArrayList of Goal objects tracked for the experiment.
mainGoalObjectGoal object representing the main goal of the experiment.
triggeredBooleanBoolean equal to true if the experiment was triggered on the page, else to false.
activeBooleanBoolean equal to true if the experiment is currently active on the page, else to false.
triggeredInVisitBooleanBoolean equal to true if the experiment was triggered in the current visit, else to false. This means that the visit fulfilled the experiment's segment conditions at some point.
activatedInVisitBooleanWhen true, the engine activated the experiment during the current visit. A triggered experiment does not guarantee activation; factors like traffic exclusion or capping can prevent activation.
nonExpositionReasonStringIf experiment was triggered but not activated, this field represents the reason for the non exposition. Possible values are: EXPERIMENT_EXCLUSION (the visitor is part of the population excluded from the current experiment, ie he will not be counted towards the experiment results), VISITOR_CAPPING (the visitor has reached a capping preventing the activation of the experiment). This property is available if the experiment was triggered on the current page and the active property is false, else it will be null.
associatedVariationObjectVariation object associated with the experiment for the given visitor. If the experiment is not yet activated, this will usually be null, except if a pre-allocation was performed.
redirectProcessedBooleanWhen true, a URL redirection occurred for this experiment on the previous page. This property is set via processRedirect() or manual configuration. In JavaScript-based integrations, redirects may cancel further code execution; check this property to resend network requests on the landing page if necessary.

A Personalization object represents a Kameleoon personalization action for a specific segment. Core properties include the segment (trigger conditions) and the associated single variation. The Variation object contains the JavaScript and CSS code implementing the personalization action.

Properties
NameTypeDescription
idNumberID of the personalization.
nameStringName of the personalization.
dateLaunchedNumberTime of first launch of the personalization (UTC format - ms since 1st January, 1970).
dateModifiedNumberTime of last modification of the personalization (UTC format - ms since 1st January, 1970).
targetSegmentObjectSegment object associated with the personalization.
goalsArrayList of Goal objects tracked for the personalization.
mainGoalObjectGoal object representing the main goal of the personalization.
triggeredBooleanBoolean equal to true if the personalization was triggered on the page, else to false.
activeBooleanBoolean equal to true if the personalization is currently active (displayed) on the page, else to false.
triggeredInVisitBooleanBoolean equal to true if the personalization was triggered in the current visit, else to false. This means that the visit fulfilled the personalization's segment conditions at some point.
activatedInVisitBooleanBoolean equal to true if the personalization's action was actually displayed (executed) in the current visit, else to false. Note that a triggered personalization does not necessarily imply that the associated action was displayed, since several additional factors can affect the execution of the action. For instance, capping options may prevent the execution, or the visitor may be part of a control group for this personalization (in which case Kameleoon also does not display the personalization's action).
nonExpositionReasonStringReason for non-exposition if triggered but not displayed. Possible values: GLOBAL_EXCLUSION, PERSONALIZATION_EXCLUSION, PRIORITY, SCHEDULE, PERSONALIZATION_CAPPING, VISITOR_CAPPING, SCENARIO, and SIMULATION. This property is available if the personalization triggered on the current page and active is false.
associatedVariationObjectAssociated Variation object. This property always references a valid object for personalizations.

An ExperimentActivation object represents an experiment activated during a specific visit. Because visits can be historical, the associated experiment may have stopped. In such cases, the engine does not inject experiment metadata (name, launch date, segment) into the application file, making it unavailable via the API. However, IDs always remain available.

Properties
NameTypeDescription
experimentIDNumberID of the experiment.
associatedVariationIDNumberID of the associated variation. If the associated variation is the reference (control), the ID is equal to 0.
associatedVariationObjectAssociated Variation object. This property is null if the experiment or variation is no longer active (stopped or paused).
timesArrayList of activation times for this experiment on this visit (UTC format - ms since 1st January, 1970).

A PersonalizationActivation object represents a personalization activated during a specific visit. Similar to experiments, metadata is unavailable if the personalization has stopped, though IDs remain accessible.

Properties
NameTypeDescription
personalizationIDNumberID of the personalization.
associatedVariationIDNumberID of the associated variation.
personalizationObjectAssociated Personalization object. This property is null if the personalization is no longer active (stopped or paused).
associatedVariationObjectAssociated Variation object. This property is null if the personalization or variation is no longer active (stopped or paused).
timesArrayList of activation times for this personalization on this visit (UTC format - ms since 1st January, 1970).

A Variation object represents a component of an Experiment. An A/B test contains multiple variations (e.g., A/B test with one variation plus reference, A/B/C test with two plus reference). Personalizations associate with a single Variation object.

note

During variation code execution, the this keyword references the corresponding Variation object. Use this reference to navigate the object hierarchy (e.g., via the associatedCampaign property).

Properties
NameTypeDescription
idNumberUnique id of the variation. If the variation represents the reference (control), the ID is equal to 0.
nameStringName of the variation. If the variation represents the reference (control), the name is equal to "Reference".
associatedCampaignObjectThe Experiment or Personalization object linked to this variation.
instantiatedTemplateObjectInstantiated template object from which this variation was built, if applicable. If the variation was not built from a template, this property is null.
reallocationTimeNumberTime of the last traffic reallocation performed for the variation (UTC format - ms since 1st January, 1970). If a reallocation was never performed, the value will be null.

A Template object represents an instantiated Widget template. Use templates to generate variations from a common codebase via the Kameleoon app interface. A Template object contains predefined fields and their values for the associated variation.

Properties
NameTypeDescription
nameStringName of the base template.
customFieldsObjectMap corresponding to the template data. The keys of the map are the names of the fields defined in the base template. The values are the actual instantiated values entered by the user for the associated variation. For instance, if a template was created with a single field "currentDiscount" of text type, customFields could be equal to the object {"currentDiscount": "-10% on all orders today!"}.

A Goal object represents a Key Performance Indicator (KPI) defined in the Kameleoon app.

Properties
NameTypeDescription
idNumberID of the goal.
nameStringName of the goal.
typeStringType of the goal. Possible values are: CLICK, SCROLL, URL, ENGAGEMENT and CUSTOM.

A Segment object contains criteria that a visit must fulfill to belong to the segment. On the Kameleoon platform, segments include constant conditions (e.g., age, location) and triggering conditions (e.g., time on page, cart contents).

Properties
NameTypeDescription
idNumberID of the segment.
nameStringName of the segment.

A Product object describes items in a catalog. Most properties are optional and may be null.

Properties
NameTypeRequiredDescription
idStringTrueUnique ID of the product.
nameStringFalseName of the product.
skuStringFalseStock Keeping Unit (SKU) of the product.
categoriesArrayFalseList of Category objects
imageURLStringFalseThe URL of the main image for this product.
priceNumberFalseThe current price of the product.
oldPriceNumberFalseThe original price of the product, usually before discounts or promotions.
brandStringFalseName of the product's brand.
descriptionStringFalseTextual description of the product.
availableBooleanFalseIndication whether the product is in stock.
availableQuantityNumberFalseCurrent stock of the product.
ratingNumberFalseRating (usually from 0 to 5, but can be any number) attributed to the product.
tagsArrayFalseList of tags (as Strings) for this product.
typePrefixStringFalseProduct type (e.g., "mobile phone", "washing machine"). Used by search algorithms.
merchantIDStringFalseSeller / merchant ID of this product (in case your website operates a marketplace).
groupIdStringFalseUse this field to combine product variants into one group.
modelStringFalseModel of the product.
leftoversStringFalseIndication of how much inventory of a particular product is available. It can take one of the following values: one (the product is available in a single copy), few (the product is in limited quantities – up to 10 units), lot (available from 10+ units of the product).
priceMarginNumberFalseA weighting factor of the product price margin, between 0 and 100.
isFashionBooleanFalseSet to true for clothing products.
isChildBooleanFalseUse this field if child product.
isNewBooleanFalseUse this field if new product.
accessoriesArrayFalseArray of product IDs that can be complementary or equivalent to the current product.
seasonalityArrayFalseArray of integers (months: 1-12).
paramsArrayFalseList of Param objects
fashionObjectFalseFashion object
autoObjectFalseAuto object

Properties of the category object

Properties
NameTypeRequiredDescription
idStringTrueUnique ID of the category.
nameStringFalseName of the category.
parentStringFalseUnique ID of the parent category.
urlStringFalseThe URL of the category.

Properties of the param object

An optional generic field that allows users to upload custom information about a production that would not "fit" in other fields. For instance, such an information could be the membership status required to buy a given product, or departure & return dates for a travel circuit.

Properties
NameTypeRequiredDescription
nameStringTrueName of the param.
valueArrayTrueList of value (as Strings).
unitStringFalse

Properties of the fashion object

An optional generic field that allows users to upload custom information about the product.

Properties
NameTypeDescription
genderStringMust be “f” (Female) or “m” (Male).
typeStringProduct type. Possible values: shoe, shirt, tshirt, underwear, trouser, jacket, blazer, sock, belt, hat, glove.
featureStringUse this field to indicate if the product is for adults or kids only. Must take the value “child” or “adult”.
colorsArrayList of Color objects.

Properties of the color object

Properties
NameTypeDescription
colorStringProduct colors.
pictureStringThe URL of the picture.

Properties of the auto object

An optional generic field that allows users to upload custom information about the product.

Properties
NameTypeDescription
vdsArrayArray that contains the Vehicle Identification Numbers (VIN) that serves as the car’s fingerprint.
compatibilityArrayContains a list of Compatible object

Properties of the compatible object

Properties
NameTypeRequiredDescription
brandStringTrueCar brand name.
modelStringFalseCar model name.