Skip to main content

API Reference

Kameleoon.API.Core

This module contains the essential functions you can use to implement front-end A/B testing variations without any flickering effect. It is extremely important to use these methods in the correct order. Many front-end developers working with Kameleoon will already be familiar with these concepts. This module also contains several methods used to initialize the engine. For example, methods related to privacy laws and legal consent collection.

Before calling the Activation API JavaScript object, it's important to make sure that the Kameleoon Engine has loaded. However, if you need to perform actions like sending tracking data, triggering experiments, or changing visitor attributes, you can use the Kameleoon Command Queue object. This allows for delayed command execution: instead of calling the Activation API directly with the Kameleoon.API JavaScript object, you pass commands and functions to the kameleoonQueue object. If the Kameleoon engine has already loaded, the commands or functions will be executed right away. Otherwise, they'll be added to a queue and executed later when the engine is ready. To learn more about this feature, refer to the Command queue documentation.

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 once you have obtained legal consent from the visitor to activate Kameleoon. It triggers the activation of Kameleoon's normal mode. For more information, refer to the Consent management article.

Arguments
NameTypeDescription
moduleStringname of the module you want to enable (can be either "AB_TESTING", "PERSONALIZATION", or "BOTH"). This field is optional, if not provided, the method will activate legal consent for both modules.

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 once you know that the visitor declines the use of Kameleoon. It disables Kameleoon normal operation mode. For more information, please refer to this article.

Arguments
NameTypeDescription
moduleStringname of the module you want to disable (can be either "AB_TESTING", "PERSONALIZATION", or "BOTH"). This field is optional, if not provided, the method will activate legal consent for both modules.

enableSinglePageSupport

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

The enableSinglePageSupport() method triggers a reload of the Kameleoon engine when the active URL changes, even if there is no actual browser page load involved. If your website is a Single Page Application with different URLs but a single initial page load, the use of this method is recommended. Every URL change will then be considered as a new page by Kameleoon. This will enable URL targeting to work, as well as the correct gathering of some information, such as the number of 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 when an element on the page has changed and reapplies all Kameleoon changes created with the Graphic Editor. This is useful in Single Page Applications that dynamically insert, remove, or modify elements in the Document Object Model (DOM) without changing the URL or reloading the page. Using this method can prevent a dynamic change from unintentionally removing your experiment after a dynamic update. For other types of Single Page Applications, see enableSinglePageSupport().

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. This objects holds global, constant values related to the current configuration of Kameleoon on this site.

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 initalizes the Kameleoon engine. It is normally called automatically when the Kameleoon application file loads, at each page load. However, sometimes it is useful to call it manually. The example on the right shows for instance how you could implement reloading after each URL change (similar to what the enableSinglePageSupport() method does).

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 sends the browser to another URL. It is generally used in split A/B experiments. Note: do not write code such as window.location.href = redirectionURL; for your split experiments. Always use this method as it takes care of some important details (like ensuring proper tracking) in the background.

note

If the redirection URL is on a domain other than the base URL, and Kameleoon installation does NOT include unified session data, an additional URL parameter of the form kameleoonRedirect-{experimentID} will be added to the target URL. This is normal and mandatory to get tracking correctly working.

Arguments
NameTypeDescription
redirectionURLStringURL of the new page where the visitor will be redirected. 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 will execute a JavaScript function (callback) as soon as the conditionFunction function returns true. It periodically calls the conditionFunction with a polling mechanism, so its use can result in flickering. For this reason, we strongly recommend the use of the next method, runWhenElementPresent(), over the use of this method. See the description of runWhenElementPresent() for more details.

Arguments
NameTypeDescription
conditionFunctionFunctionJavaScript function to execute, which must return true or false. This field is mandatory.
callbackFunctionJavaScript function to execute when the conditionFunction function returns true. This field is mandatory.
pollingIntervalNumberPolling interval, in milliseconds. Kameleoon will execute the conditionFunction function periodically with this interval. If you cannot use runWhenElementPresent(), and are forced to rely on runWhenConditionTrue(), providing a lower number for the pollingInterval argument can reduce flickering (at the expense of CPU browser usage). This field is optional, if not provided, the method will use the default value of 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 our previous modification.
Kameleoon.API.Core.runWhenElementPresent(".product-button", function (elements) {
elements.forEach(element => {
element.innerText = "Add To Cart";
});
}, null, true);

The runWhenElementPresent() method executes a JavaScript function (callback) as soon as a specific element appears in the DOM. Technically, it uses Mutation Observers and is the core method enabling the use of our Anti-Flickering technology. When implementing front-end A/B experiments, you should try to determine which are the key elements you need to act on for your variation. Then always call runWhenElementPresent() with a key element as the first argument and the variation implementation code in a callback as the second argument. Kameleoon then ensures all your modification code runs as soon as the desired HTML element appears in the DOM, before any display refresh cycle is initiated by the browser.

If your code needs to act on several elements, which is often the case, it is better to call runWhenElementPresent() several times with different arguments rather than trying to guess which element will appear last and use runWhenElementPresent() once with this element. If called a single time, flickering can appear if a refresh cycle happens between the appearance of the "first" element that needs to be visually modified and the "last" element (given as argument to the method).

Important note: one of the additional optional arguments is pollingInterval. If provided, mutation observers (or anti-flickering) will be disabled and our previous, legacy mechanism relying on pollers will be used instead (with the given polling interval). Since it could result in noticeable flickering, we do not recommend providing this argument except in very special cases (complex selector queries that would have a huge impact on the CPU browser usage, for instance).

Arguments
NameTypeDescription
selectorStringCSS selector of the element. To specify multiple CSS selectors, provide a single comma-separated string. The callback function is called if one or more of the elements is present. This field is mandatory.
callbackFunctionJavaScript function to execute when the element appears in the DOM. This field is mandatory.
pollingIntervalNumberPolling interval, in milliseconds. Providing this argument is not recommended as it will disable Kameleoon's use of mutation observers. Instead, the legacy polling implementation will be used: the engine will periodically issue selector queries to determine if the element is present on the DOM or not. It can result in flickering. This field is optional.
isDynamicElementBooleanEnables dynamic element support and single page app support. If the specified CSS selector of the element is not found by Kameleoon when the page loads, Kameleoon keeps track of the selector and executes the callback function when the element appears in the DOM. If a new element with that selector appears on the page, Kameleoon executes the callback again with the new element. For example, this setting is useful if your site has dynamic menus, infinite scrolling, or popups. 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 will execute a JavaScript function (callback) as soon as a specific element appears in the shadow DOM only for 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.
isDynamicElementBooleanEnables dynamic element support. If the specific element is not currently on the page, Kameleoon keeps track of the selector. If a new element with that selector appears on the page, Kameleoon executes the callback again with the new element. For example, this setting is useful if your site has dynamic menus, infinite scrolling, or popups.

Kameleoon.API.Goals

This module manages the triggering of goals and conversion data. For instance, a confirmed purchase with a generated revenue would have to be registered and implemented with this module.

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 allows you to cancel a conversion that was previously triggered during the same visit. It cannot cancel conversions registered in previous visits.

Arguments
NameTypeDescription
goalNameOrIDString or NumberName (String) or ID (Number) of the goal as it is defined in the Kameleoon app (in the Goals configuration section). This field is mandatory.

processConversion

Kameleoon.API.Core.runWhenElementPresent("#buyButton", ([buyButton]) => {
Kameleoon.API.Utils.addEventListener(buyButton, "click", () => {
Kameleoon.API.Goals.processConversion("GOAL_ID", 19.99);
});
})

The processConversion() method allows you to trigger a conversion.

note

If you're initiating a conversion from a Tag Management System (for example, Google Tag Manager), we recommend using the Kameleoon Command Queue, which allows you to delay the command's execution until the Kameleoon engine finishes loading. Once loaded, the engine executes all the commands in the queue, in the order they were pushed. For example:

window.kameleoonQueue = window.kameleoonQueue || [];
kameleoonQueue.push(['Kameleoon.API.Goals.processConversion', 'GOAL_ID']);
Arguments
NameTypeDescription
goalNameOrIDString or NumberName (String) or ID (Number) of the goal as it is defined in the Kameleoon app (in the Goals configuration section). Be careful: if you use a name, this name must be unique among your goals! This field is mandatory.
revenueNumberAmount of the transaction. If you provide this number, Kameleoon will register the amount of the purchase / transaction (allowing the reporting of metrics such as generated revenue, average cart amount, etc). This field is optional.

Kameleoon.API.Data

This module contains mainly methods to set custom datas, which are the preferred way to provide additional customer or visit characteristics. Other methods are also related to data management (obtain and write data in Kameleoon 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 allows you to read local data previously stored on the visitor's web browser via the writeLocalData() method. Underneath, our engine will read this data on our unified Local Storage. You don't have to worry about the usual limitations of the Local Storage - our implementation removes them.

Arguments
NameTypeDescription
keyStringKey (name) of the data to return. 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). It consists in a call to our Data API that retrieves a list of visits stored on our backend servers for this visitor. It then writes all these visits in the LocalStorage and ensures that this data is properly accessible via the Activation API or usable for targeting purposes. This method is generally used for cross-device history reconciliation or ITP purposes on Safari and is triggered automatically in those contexts, so it should normally not be called manually.

Arguments
NameTypeDescription
keyStringKey (name) of the custom data to use as a mapping identifier (unique identifier on your side, such as an account id or email). This field is optional, if not provided, the method will use the default custom data that was configured as a unique identifier for cross-device history reconciliation in the Kameleoon app.
valueStringValue corresponding to the current visitor identifier (used in the call to the Data API). This field is optional, if not provided, the method will use the current value of the custom data provided as first argument.
currentVisitOnlyBooleanIf set, the SSC call will only ask data related to the current visit. This optimization is useful if you perform a SSC only to refresh the value of a custom data acquired via the Data API / Server to Server integration. This field is optional, if not provided, the method will use the default value of false.

resetCustomData

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

The resetCustomData() method allows you to reset a custom data.

Arguments
NameTypeDescription
nameStringName of the custom data as it is defined in the Kameleoon app (in the Custom Data configuration section). 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 allows you to retrieve data (according to a key passed as argument) stored on a remote Kameleoon server. Usually data will be stored on our remote servers via the use of our Data API. This method, along with the availability of our highly scalable servers for this purpose, provides a convenient way to quickly store massive amounts of data that can be later retrieved for each of your visitors / users.

Note that since a server call is required, this mechanism is asynchronous, and you must pass a callback as argument to the method.

Arguments
NameTypeDescription
keyStringkey. 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

Kameleoon.API.Data.setCustomData("myCustomDataName", "myNewValue");

The setCustomData() method allows you to set a custom data value.

Arguments
NameTypeDescription
nameStringName of the custom data as it is defined in the Kameleoon app (in the Custom Data configuration section). This field is mandatory.
valueString, Number, or BooleanValue of the custom data. The argument provided should match the type declared for this custom data in the Kameleoon app. This field is mandatory.
overwriteIfCollectionBooleanIf the custom data is a collection (of type List or Count List), by default, the value provided is added as a new element to the existing list. Both the new custom data entry and any existing entries in the list will be available for targeting and reporting. If this boolean is set to true, the list will be reset and the argument will be added as the first element of a new list. Only the new custom data entry will be available for targeting and reporting. If the existing custom data is not a collection (type List or Count List), then the existing data is always overwritten, and this boolean has no impact on targeting or reporting. To empty the list without adding new data, use the resetCustomData() method instead. This field is optional, if not provided, the method will use the default value of false.

writeLocalData

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

The writeLocalData() method allows you to write local data on the visitor's web browser and later retrieve it via the readLocalData() method. Underneath, our engine will write this data as unified session data in Local Storage. You don't have to worry about the usual limitations of the Local Storage - our implementation removes them. The data passed will be available immediately for retrieval (in the same browser tab), as it is cached in RAM, but please note that the actual associated write happens asynchronously.

Arguments
NameTypeDescription
keyStringKey (name) of the data to write. This field is mandatory.
valueStringValue of the data to write. This field is mandatory.
persistentBooleanSet the data as persistent or not. If not persistent, this data will be only saved for 1 hour, after which it won't be available. If persistent, this data will be saved for 30 days. This field is optional, if not provided, the method will use the default value of false.

Kameleoon.API.Events

This module allows developers to trigger custom events that can be used in the targeting of your experiments and personalizations. Note that our API also offers standard DOM events which are documented here.

trigger

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

The trigger() method allows you to trigger a custom event. Custom events are used in targeting segments.

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

Kameleoon.API.Tracking

This module allows the integration of Kameleoon results with 3rd party tracking & analytics platform (such as Adobe 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;

We provide a native integration with Adobe Omniture if you wish to track results of your experiments and personalizations on Omniture. To use this bridge, you must modify the file containing the s_doPlugins() code as shown in the example on the right. Two important things need to be done inside the s_doPlugins() function:

  • add a mandatory call to the Kameleoon.API.Tracking.processOmniture() method;
  • set a global variable, window.kameleoonOmnitureCallSent, to true so that we can know when a first tracking call has been sent. You can also set this variable on your own somewhere else if you wish, but it is recommended to set it on the s_doPlugins() code.

With our integration, Kameleoon will try to minimize the number of overall Omniture hits sent (which is important, since the number of hits directly affects Omniture pricing). It will only send an additional hit if an experiment or personalization triggers after the main Omniture call has already been processed and sent. This can happen either if Kameleoon loads after the Omniture code (not recommended and should not be the case, but possible since Kameleoon's application file usually loads asynchronously) OR if there is an experiment or personalization triggering "late" (ie, not at page load, but for instance after a click on a button).

In the normal case, where Kameleoon loads first and all active experiments can be known at page load, all the additional data is sent along the global, standard Omniture tracking call.

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 is an entry point to interact with your product catalog. For instance, it can be used to register a product view or purchase, add a product to the cart, obtain a set of automatic product recommendations, or obtain statistics about a given product (how many times it was bought or viewed in the last hour or day).

note

This module is only available if you suscribed to the Product Recommendation module or the 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 will retrieve recommended products as computed by the specified algorithm. They are retrieved by an asynchronous server call.

caution

This method will only return meaningful results if a correct tracking of products (use of trackProductView(), trackCategoryView(), etc) has been implemented.

Arguments
NameTypeDescription
codeStringUnique code of the recommendation block.
paramsObjectParameters to control the data returned by the recommendation platform.
successCallbackFunctionA callback function, to which the API response will be passed. Response type: object. This field is mandatory.
errorCallbackFunctionA callback function that will be called in case of error. This field is optional.

Parameters to control the data returned by the recommendation platform

NameTypeDescription
itemNumberID of the current product. Mandatory with the algorithms "Similar" and "They also bought this product".
excludeArrayThis field is optional. A comma-separated list of product identifiers that must be excluded from the recommendation.
extendedNumberThis field is optional. If "1", it will return all details about recommended products. If omitted, it returns only products IDs.
categoryNumberMandatory when using algorithms on a category page. It returns the products recommended only from 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 HTML code for the block with products. You can 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);
});

The trackAddToCart() method should be called when a product is added to the visitor's shopping cart.

Arguments
NameTypeDescription
productIDStringProduct identifier. This can be any unique identifier for this particular product. This field is mandatory.
unitPriceNumberPrice for a single unit of the product referenced by productID. This field is optional, if not provided, a default value of 0.0 will be used. This means that the cart total amount won't change.
quantityNumberQuantity of products added to the cart. Note that you can provide a negative value: in this case the product will be considered removed from the cart, not added. This field is optional, if not provided, the method will use the default value of 1.

trackAddToWishList

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

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

Call the trackAddToWishList() method when the user adds or removes an product from their wish list (or favorites).

NameTypeDescription
productIdStringThe unique identifier of the product that the user added to their wishlist. This field is mandatory.
quantityNumberQuantity of the product to add to the wish list. To indicate the user removed a product quantity from their wish list, you can use negative values (for example, -1). This field is optional. If not specified, the method uses the default value of 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 should be called every time a category page is viewed by the visitor during his browsing session.

Arguments
NameTypeDescription
categoryIDStringCategory identifier. This can be any unique identifier for this particular category. 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 should be called every time a product is viewed by the visitor during his browsing session. Note that by ensuring this call is properly made, Kameleoon will be able to build a copy of your product catalog without the need for an explicit integration via a XML feed for instance. This can greatly facilitate the setup and launch of a product recommendations project, since all the integration work can take place only on the front-end.

Arguments
NameTypeDescription
productIDStringProduct identifier. This can be any unique identifier for this particular product. This field is mandatory.
productDataObjectProduct object. This field is mandatory if you use our Product Recommendation add-on and want to use this method to import your product feed to Kameleoon.

trackSearchQuery

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

Use the trackSearchQuery() method to record when a user makes a search query.

Arguments
NameTypeDescription
search_queryStringThe value of the search query. This argument is mandatory

trackTransaction

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

The trackTransaction() method should be called when a purchase / transaction is actually carried out.

Arguments
NameTypeDescription
productsArrayList of objects that contains the productID and quantity for each product in the transaction. This field is mandatory.

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() methods retrieves personalized instant search results from the Kameleoon Search solution. Results are retrieved by an asynchronous server call.

Arguments
NameTypeDescription
search_queryStringThe search query provided by the user. This field is mandatory.
successCallbackFunctionA callback function to which the API response is passed. The response type is Object. This field is mandatory.
errorCallbackFunctionA callback function that is called when there is an error. 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",
page: 2,
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_queryObjectThe search query provided by the user with optional filter parameters. See the next section for available parameters. This field is mandatory.
successCallbackFunctionA callback function to which the API response is passed. The response type is Object. This field is mandatory.
errorCallbackFunctionA callback function that is called when there is an error. This field is optional.
Parameters to filter results
NameTypeDescription
search_queryStringThe search query string provided by the user.
pageNumberMaximum number of pages.
limitNumberMaximum number of results per page.
brandsArrayComma-separated list of brand names to include in the results.
categoriesArrayComma-separated list of category IDs to include in the results.
filtersObjectOptional escaped JSON string with filter parameters. For example:{"bluetooth":["yes"],"offers":["15% cashback"],"weight":["1.6"]}
sort_byStringField to sort the results by. Accepts the values popular, price, discount, sales_rate, and date.

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 should called to obtain count of products which were sent via trackProductView(), trackTransaction(), trackAddToCart()

Arguments
NameTypeDescription
eansArrayproduct id or list of product id (as Strings)
callbackFunctionfunction to return product data
timeBeginNumberbeginning of date range (UNIX milliseconds timestamp)
timeEndNumberend of date range (UNIX milliseconds timestamp)

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 should called to obtain products which were sent via trackProductView()

Arguments
NameTypeDescription
eansArrayproduct id or list of product id (as Strings)
callbackFunctionfunction to return product data
parametersObjectobject with some parameters to retrieve specific field. The field is optional. Default value = { all: true }

Kameleoon.API.Experiments

This module provides a collection of entry points to access the current live experiments ran by Kameleoon.

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);

This method forces the association of a given variation for an experiment, instead of relying on the standard allocation algorithm (which usually picks a variation at random according to the configured deviation). Note that this method can be called before the experiment is actually triggered. In this case, the variation will be "pre-allocated", which means that if the experiment later triggered in the current visit (or even a future one), this variation will be the one chosen. If the experiment was already previously triggered, a variation is normally already associated with the experiment. You should set the override argument to true if you want to replace it with the new one - else the method won't do anything.

Arguments
NameTypeDescription
experimentIDNumberID of the experiment. This field is mandatory.
variationIDNumberID of the variation. This field is mandatory.
overrideBooleanSpecifies if an existing variation association (for an already triggered experiment) should be forgotten and replaced by the new one provided. This field is optional, if not provided, the method will use the default value of 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);

This method will block an experiment. Further triggering / activation of this experiment will not be possible, even explicitely via the use of methods such as trigger(). The block will be set for the current page (until the next Kameleoon.API.Core.load()) by default. It can be set for the whole visit by setting the visit argument to true.

Arguments
NameTypeDescription
experimentIDNumberID of the experiment. This field is mandatory.
visitBooleanSpecifies if the experiment will be blocked for the whole visit instead of the current page. This field is optional, if not provided, the method will use the default value of false.

getAll

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

Returns the list of experiments currently live in your website (ie, the experiments that are not in draft, paused or stopped, but actually running).

Return value
NameTypeDescription
experimentsArrayList of Experiment objects.

getActive

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

Returns the list of active experiments for the current visit and page. An active experiment means that its variation code has been executed in the current browser context (page). If the experiment was activated on a different URL but is not active in the current URL, it won't be returned by this method. You can however retrieve it via the getActivatedInVisit() method.

Return value
NameTypeDescription
experimentsArrayList of Experiment objects.

getById

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

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

Returns the experiment with a specific 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);
}

Returns the experiment with a specific 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);
}
});

Returns the list of experiments that were triggered in 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);
}
});

Returns the list of experiments that were activated in the current visit.

Return value
NameTypeDescription
experimentsArrayList of Experiment objects.

trigger

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

This method forces the trigger of a given experiment, independently of the targeting segment. In practice, this will have the same effect as if conditions for the targeting were fulfilled. Note that this triggers the experiment, but not necessarily activates it.

Arguments
NameTypeDescription
experimentIDNumberID of the experiment. This field is mandatory.
trackingOnlyBooleanSpecifies if normal execution of the variation assets should take place (JavaScript code, CSS code, URL redirections, graphical editor changes), or if only tracking should be performed for this experiment. Usually, this option is set to true when dealing with an hybrid experiment, where the implementation is done on the back-end but tracking / analytics is done on the front-end. This field is optional, if not provided, the method will use the default value of false.

Kameleoon.API.Personalizations

This module provides a collection of entry points to access the current live personalizations ran by Kameleoon.

disable

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

The disable() method should be used to mark a personalization as disabled. For instance, if you create a personalization that will display a pop-in or similar visual artefact that can be closed, if the user actually closes the pop-in by clicking on the close button, the underlying personalization should be marked disabled, as it is no longer active. Note that pop-ins automatically generated by Kameleoon (ie, not via custom JavaScript code, but via our interface) already implement a call to this method on a click on the close button.

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");
}

Returns the list of active personalizations for the current visit and page. An active personalization means that its variation code has been executed in the current browser context (page) and that the associated displayed action is still visible on the page. If the personalization was triggered on a different URL but is not active in the current URL, it won't be return by this method. Similarly a personalization displaying a pop-in that was already closed won't be returned. You can however retrieve such personalizations via the getTriggeredInVisit() method.

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);
}
});

Returns the list of personalizations currently live in your website (ie, the personalizations that are not in draft, paused or stopped, but actually running).

Return value
NameTypeDescription
personalizationsArrayList of Personalization objects.

getById

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

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

Returns the personalization with a specific 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);
}

Returns the personalization with a specific 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);
}
});

Returns the list of experiments that were triggered in 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);
}
});

Returns the list of experiments that were activated in the current visit.

Return value
NameTypeDescription
personalizationsArrayList of Personalization object.

trigger

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

This method forces the trigger of a given personalization, independently of the targeting segment. In practice, this will have the same effect as if conditions for the targeting were fulfilled. Note that this triggers the personalization, but not necessarily activates it.

Arguments
NameTypeDescription
personalizationIDNumberID of the personalization. This field is mandatory.
trackingOnlyBooleanSpecifies if normal execution of the variation assets should take place (JavaScript code, CSS code, URL redirections, graphical editor changes), or if only tracking should be performed for this personalization. Usually, this option is set to true when dealing with a personalization implemented outside of Kameleoon, but where targeting and/or tracking is performed via Kameleoon. This field is optional, if not provided, the method will use the default value of false.

Kameleoon.API.Variations

This module contains methods to deal with 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);
}
});
}

Execute JS code and apply CSS for the variation corresponding to the ID passed as argument.

Kameleoon.API.Segments

This module contains methods to deal with segments and targeting.

getAll

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

Returns the list of segments currently live in your website: the ones associated with experiments, personalizations, and the ones marked for tracking in Audiences.

Return value
NameTypeDescription
segmentsArrayList of Segment objects.

getById

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

Returns the segment with a specific 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");

Returns the segment with a specific 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);
}
});

This method forces a re-evaluation of the given segment targeting conditions. Targeting conditions are usually evaluated as soon as it is possible (mostly at page load) and can be set to true, false, or undefined (still waiting). Calling this method will re-evalute all conditions immediately, as if Kameleoon engine was initialized again at page load.

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

trigger

Kameleoon.API.Segments.trigger(12345);

This method forces the trigger of a given segment for the current visitor, independently of the targeting conditions. In practice, this will have the same effect as if conditions for the targeting were fulfilled.

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

Kameleoon.API.Utils

This module contains several helper methods that can be useful for various 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

All event listeners created with this API will be reset (cleared) when Kameleoon will reload. Thus we recommend to use that method to add an Event Listener to an element, in the context of a Single Page Application (SPA) website.

Arguments
NameTypeDescription
elementObjectThe element on which you want to add a listener. This field is mandatory.
eventTypeStringA String that specifies the name of the event. This field is mandatory.
callbackFunctionCallback function that will be called 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 to the specified element. The interest of this method is that it will listen both for mouse clicks (for a desktop computer) and for touchdown events (in mobile phones and tablets). Technically, since touchdown events are not part of the specification, we consider a touchdown occured on mobile if a touchstart event was received, followed by a touchend event without a touchmove event between.

note

All listeners created with this API will be reset (cleared) when Kameleoon will reload. Thus it can be useful in the context of a Single Page Application (SPA) website.

note

On desktop devices, a right click on the mouse will trigger this method. This is normal and expected (usually a right click will lead to an opening in a new tab for instance).

Arguments
NameTypeDescription
elementObjectThe element on which you want to add a listener. This field is mandatory.
callbackFunctionCallback function that will be called 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 with the setInterval() method.

Arguments
NameTypeDescription
intervalIdNumberThe id of the timer 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 with the setTimeout() method.

Arguments
NameTypeDescription
timeoutIdNumberThe id of the timer returned by the setTimeout() method. This field is mandatory.

computeHash

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

The computeHash() method computes a hash from a given string. This is useful if you want to work on unique data, without having to directly manipulate the original data (especially personal data, for legal reasons).

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 parameters found. This method works with 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 can be used to initiate a call with 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.
timeoutNumberThe time to wait in milliseconds before cancelling the request. This field is optional, if not provided, the method will use the default value of 5000 milliseconds.

querySelectorAll

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

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

The querySelectorAll() method returns all elements in the document that match a specified CSS selector(s), as a static NodeList object.

note

This method support 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 calls a function or evaluates an expression at the specified interval (in milliseconds).

note

All intervals created with this API will be reset (cleared) when Kameleoon will reload. Thus it can be useful in the context of a Single Page Application (SPA) website.

Arguments
NameTypeDescription
functionFunctionJavaScript function that will be executed periodically. This field is mandatory.
millisecondsNumberNumber of milliseconds for the interval. This field is optional, if not provided, the method will use the default value of 200 milliseconds.
Return value
NameTypeDescription
intervalIdNumberID that can be used as the argument to the clearInterval() method to cancel the timer.

setTimeout

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

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

note

All timeouts created with this API will be reset (cleared) when Kameleoon will reload. Thus it can be useful in the context of a Single Page Application (SPA) website.

Arguments
NameTypeDescription
functionFunctionJavaScript function that will be executed periodically. This field is mandatory.
millisecondsNumberNumber of milliseconds to wait before executing the given function. This field is optional, if not provided, the method will use the default value of 200 milliseconds.
Return value
NameTypeDescription
timeoutIdNumberID that can be used as the argument to the clearTimeout() method to cancel the timer.

Kameleoon.API.Visitor

This module provides a shortcut to obtain a reference to the current Visitor object. There is only a single, unique Visitor object within the Activation API. You can also override the visitor code set by Kameleoon.

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>")
});

This method overrides the Kameleoon VisitorCode, which is a unique identifier that Kameleoon randomly generates for every visitor. Ensure that the ID you provide is unique to the visitor and does not exceed 255 characters in length.

It is critical that you call this method as early as possible. Specifically, make sure you call this method before any experiments are triggered by Kameleoon. If you update the VisitorCode with your own ID value after Kameleoon has already assigned a variation to the user, Kameleoon will reassign the user to a new variation.

Kameleoon.API.CurrentVisit

This module is just a shortcut to obtain a reference to the current (in-progress) Visit object. It is the reference to the same object that you would obtain by calling 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).
singlePageSupportBooleanEquals true if Single Page Support was configured for this website. This can be done either globally using the Kameleoon app, or using the Kameleoon.API.Core.enableSinglePageSupport() method in the Activation API. Single Page Support means any changes in the URL will trigger Kameleoon.API.Core.load(), even if no browser page load is involved.
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 data scoped to the visitor, that is not dependent of a given visit. Note that this object contains a list of all the Visit objects related to this 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).
numberOfVisitsNumberThe total number of visits made by this visitor on your website. It is not always equal to visits.length, since we only keep available the latest 25 visits to the Activation API.
firstVisitStartDateNumberDate (UTC format - ms since 1st January, 1970) of the start of the first visit for this visitor. It is not always equal to visits[0].startDate, since we only keep available the latest 25 visits to the Activation API.
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. It contains all the information gathered by Kameleoon, which is updated in real-time. Data can be related to the context of the visit (device used, location...), to the behavior observed during the visit (duration, number of pages viewed...) or to 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 in this visit. If your website is a Single Page Application, calling Kameleoon.API.Core.load() will increase this number. Changes in the URL will automatically trigger a Kameleoon.API.Core.load() call if you chose the Single Page Support option for your website in the Kameleoon app configuration section (or called manually Kameleoon.API.Core.enableSinglePageSupport()).
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.
kameleoonConversionScoresObjectMap of Kameleoon Conversion Scores (KCS). The keys of the map are the defined key moments names. The values are numbers from 0 to 100 representing the KCS for the given key moment.
note

The kameleoonConversionScores property is only available if you suscribed to 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. Its main properties are its segment (defining the conditions under which the experiment will be triggered) and the associated variations. Variations contain the JavaScript and CSS code that implement the changes needed to produce the desired end-result.

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 the traffic deviation currently used by the experiment. The keys of the map are the IDs of the variations in the experiment (by convention, the reference / original variation will always have an ID of 0). The values are percentage number from 0 to 100. Note that the sum of all the values in this map may not be equal to 100, since part of the traffic may be unallocated (untracked).
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.
activatedInVisitBooleanBoolean equal to true if the experiment was activated in the current visit, else to false. Note that a triggered experiment does not necessarily imply that the experiment was activated, since several additional factors can affect this activation. For instance, the visitor may be part of the traffic excluded from this experiment, or capping options may have been set.
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.
redirectProcessedBooleanBoolean equal to true if an URL redirection just occurred for this experiment (ie, took place on the previous page), else to false. It will be set by the use of the processRedirect() method or by configuring (via the interface) a variation as an URL redirect. This property is particularly useful for JavaScript based integrations, since when a redirect happens, the further execution of JavaScript code is not guaranteed (and additional network requests can be cancelled). Thus developers have to take care of this particular situation, resending those network requests on the next page after the redirect, when the boolean is set.

Personalization

A Personalization object represents a Kameleoon personalization action for a given segment. Its main properties are its segment (defining the conditions under which the personalization will be triggered and displayed) and the associated single variation. Technically, the Variation object is the same used by an Experiment. It contains the JavaScript and CSS code that implement the actual displayed 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).
nonExpositionReasonStringIf personalization was triggered but not displayed / activated, this field represents the reason for the non exposition. Possible values are: GLOBAL_EXCLUSION (the visitor is part of the population globally excluded from all personalizations), PERSONALIZATION_EXCLUSION (the visitor is part of the population excluded from the current personalization, ie he falls into the control group for this personalization), PRIORITY (another personalization has higher priority), SCHEDULE (personalization is currently off according to its schedule), PERSONALIZATION_CAPPING (the personalization has reached its global capping in terms of visitors), VISITOR_CAPPING (the visitor has reached a capping preventing the display of the personalization), SCENARIO (the personalization won't be displayed because some of the scenario conditions are not fulfilled) and SIMULATION (in the simulation mode, the non exposition was forced. This reason cannot happen in production). This property is available if the personalization was triggered on the current page and the active property is false, else it will be null.
associatedVariationObjectVariation object associated with the personalization. Note that contrary to the Experiment object, this property always links to a valid Variation object; it is never null.

ExperimentActivation

An ExperimentActivation object represents the activation of an experiment for a particular visit. It represents a loose link to the experiment object, in the sense that since the visit can be an old one, the corresponding experiment can already be stopped. In this case, the experiment common data (name, dateLaunched, targetSegment...) is not injected into the Kameleoon application file. Thus the experiment is not available via the Activation API and the experiment property will be null. However, the ids are always 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.
experimentObjectExperiment object corresponding to the activated experiment. It's very important to note that this property will be null if the experiment is currently no longer active on the site (stopped or paused).
associatedVariationObjectVariation object corresponding to the variation associated with the experiment for the given visitor. This property is null if the variation is currently no longer active on the site (corresponding experiment stopped or paused).
timesArrayList of activation times for this experiment on this visit (UTC format - ms since 1st January, 1970).

PersonalizationActivation

An PersonalizationActivation object represents the activation of an personalization for a particular visit. It represents a loose link to the personalization object, in the sense that since the visit can be an old one, the corresponding personalization can already be stopped. In this case, the personalization common data (name, dateLaunched, targetSegment...) is not injected into the Kameleoon application file. Thus the personalization is not available via the Activation API and the personalization property will be null. However, the ids are always available.

Properties
NameTypeDescription
personalizationIDNumberID of the personalization.
associatedVariationIDNumberID of the associated variation.
personalizationObjectPersonalization object corresponding to the activated personalization. It's very important to note that this property will be null if the personalization is currently no longer active on the site (stopped or paused).
associatedVariationObjectVariation object corresponding to the variation associated with the personalization for the given visitor. This property is null if the variation is currently no longer active on the site (corresponding personalization stopped or paused).
timesArrayList of activation times for this personalization on this visit (UTC format - ms since 1st January, 1970).

Variation

A Variation object represents one of the main components of an Experiment. An A/B test experiment contains a list of variations (if the test contains 1 variation in addition to the original, it is usually called an A/B test, if it has 2 variations, an A/B/C test, and so on). Note that while an Experiment contains a list of variations, a Personalization is associated to a single Variation object.

note

While executing the variation code, the this object reference is bound to the corresponding Variation object. You can thus easily obtain a reference to the current variation in your variation code, and if needed navigate the object hierarchy afterwards (for instance by using 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".
associatedCampaignObjectEither an Experiment object or a Personalization object. This object represents the campaign 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.

Template

A Template object represents an instantiated template. You can define Widget templates in the Kameleoon app. This provides an easy way to generate several variations from a common code base using a convenient visual interface. In the Activation API, a Template object contains the fields defined in the base template along with their actual instantiated values for the associated variation. There are some additional properties from the base template that are also available to use.

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!"}.

Goal

A Goal object represents a given KPI (Key Performance Indicator) that is tracked on the website. Goals are defined using 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.

Segment

A Segment object contains a list of criteria that must be fulfilled for the visit to belong to the segment. Note that on the Kameleoon platform, a Segment contains both "constant" conditions (such as age, location) and "triggering" conditions (such as the number of seconds ellapsed since the load of the page or the visit, or the total amount of items in the shopping cart).

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

Product

A Product object describes a product in your catalog, with many attached information. However, most of the properties described here are optional and can be null.

Properties
NameTypeDescription
idStringUnique ID of the product (required).
nameStringName of the product.
skuStringStock Keeping Unit (SKU) of the product.
categoriesArrayList of Category objects
imageURLStringThe URL of the main image for this product.
priceNumberThe current price of the product.
oldPriceNumberThe original price of the product, usually before discounts or promotions.
brandStringName of the product's brand.
descriptionStringTextual description of the product.
availableBooleanIndication whether the product is in stock.
availableQuantityNumberCurrent stock of the product.
ratingNumberRating (usually from 0 to 5, but can be any number) attributed to the product.
tagsArrayList of tags (as Strings) for this product.
typePrefixStringType of product (for example, "mobile phone", "washing machine", or "corner sofa"). Used by our search algorithms.
merchantIDStringSeller / merchant ID of this product (in case your website operates a marketplace).
groupIdStringUse this field to combine product variants into one group.
modelStringModel of the product.
leftoversStringIndication 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).
priceMarginNumberA weighting factor of the product price margin, between 0 and 100.
isFashionBooleanUse this field if you sell clothes products.
isChildBooleanUse this field if child product.
isNewBooleanUse this field if new product.
accessoriesArrayArray of product IDs that can be complementary or equivalent to the current product.
seasonalityArrayArray of integers (months: 1-12).
paramsArrayList of Param objects
fashionObjectFashion object
autoObjectAuto object

Properties of the category object

Properties
NameTypeDescription
idStringUnique ID of the category (required).
nameStringName of the category.
parentStringUnique ID of the parent category.
urlStringThe 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
NameTypeDescription
nameStringName of the param (required).
valueArrayList of value (as Strings) (required).
unitStringusing 2 character abbreviations for SI units : cm (centimeters), wt (watts), gr (grams), etc...

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. Can take onf of the following 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
NameTypeDescription
brandStringCar brand name (required).
modelStringCar model name.