JavaScript / TypeScript (Client-Side) SDK
Introduction
Welcome to the developer documentation for the Kameleoon JavaScript / TypeScript SDK! Our SDK gives you the possibility of running experiments and activating feature flags on your front-end JavaScript application. Integrating our SDK into your web-application is easy, and its footprint (in terms of memory and network usage) is low.
You can refer to the SDK reference to check out all possible features of the SDK. Also make sure you check out our Getting started tutorial
which we have prepared to walk you through the installation and implementation.
Latest version of the JavaScript SDK: 2.1.1 (changelog).
Getting started
This guide is designed to help you integrate our SDK in a few minutes and start running experiments in your JavaScript applications. This tutorial will explain the setup of a simple A/B test to change the number of recommended products based on different variations.
Creating an experiment
First, you must create an experiment in the Kameleoon back-office so that our platform is aware of the new A/B test you're planning to implement on your side. Make sure that server-side type is chosen as shown below:
Upon successful creation of the experiment, you will need to get its ID to use in the SDK as an argument to the triggerExperiment()
method.
Installing the SDK
Installing the JavaScript client
npm install kameleoon-client-javascript
Installing the SDK can be directly achieved through an NPM module. Our module is hosted on official npm repositories, so you just have to run the following command:
npm install kameleoon-client-javascript
Additional configuration
You can configure parameters for the JavaScript SDK via a JSON object containing configuration keys (and their associated values). You should pass this configuration object as an argument to the KameleoonClient()
constructor method. With the current version of the JavaScript SDK, those are the available keys:
- actions_configuration_refresh_interval: this specifies the refresh interval, in minutes, of the configuration for experiments and feature flags (the active experiments and feature flags are fetched from the Kameleoon servers). It means that once you launch an experiment, pause it, or stop it the changes can take (at most) the duration of this interval to be propagated in production to your servers. If not specified, the default interval is 60 minutes.
- visitor_data_maximum_size: this specifies the maximum amount of memory that the map holding all the visitor data (in particular custom data) can take (in MB on the browser LocalStorage). If not specified, the default size is 1MB.
- environment: an option specifying which feature flag configuration will be used, by default each feature flag is split into production, staging, development. If not specified, will be set to default value of production. More information
Initializing the Kameleoon client
let {KameleoonClient} = require("kameleoon-client-javascript");
let siteCode = "a8st4f59bj";
let kameleoonClient = new KameleoonClient(siteCode);
kameleoonClient = new KameleoonClient(siteCode, {"actions_configuration_refresh_interval": 5});
After installing the SDK into your application and setting up a server-side experiment on Kameleoon's back-office, the next step is to create the Kameleoon client in your application code.
The code on the right gives a clear example. A KameleoonClient is a singleton object that acts as a bridge between your application and the Kameleoon platform. It includes all the methods and properties you will need to run an experiment. The KameleoonClient needs to be initialized with an HTTP call, so all code that will use this object should be wrapped as a function callback, passed to the KameleoonClient.runWhenReady()
method. All further examples use this approach.
Initializing the Kameleoon client with configDataFile
let {KameleoonClient} = require("kameleoon-client-javascript");
let rp = require("request-promise");
let siteCode = "a8st4f59bj";
let CONFIG_DATA_URL =`https://client-config.kameleoon.com/mobile?siteCode=${siteCode}`;
let configDataFile = await rp({ uri: CONFIG_DATA_URL, json: true });
let kameleoonClient = new KameleoonClient(siteCode, {}, { configDataFile, fetchCallback });
When initializing with configDataFile
, the SDK will use the given configDataFile instead of making API call. And any time you retrieve an updated configDataFile
, just re-initialize the same client.
First, get a copy of the configDataFile
from our server. Then, initialize the client passing the configDataFile
along with fetchCallback
which is the Fetch API. This fetchCallback
is used with Fastly integration.
Triggering an experiment
let visitorCode = kameleoonClient.getVisitorCode("example.com");
let recommendedProductsNumber;
kameleoonClient.runWhenReady(function () {
let variationID;
try {
variationID = kameleoonClient.triggerExperiment(visitorCode, 75253);
}
catch (e) {
if (e.type == KameleoonException.NotTargeted.type) {
// The user did not trigger the experiment, as the associated targeting segment conditions were not fulfilled. He should see the reference variation
variationID = 0;
}
if (e.type == KameleoonException.NotActivated.type) {
// The user triggered the experiment, but did not activate it. Usually, this happens because the user has been associated with excluded traffic
variationID = 0;
}
if (e.type == KameleoonException.ExperimentConfigurationNotFound.type) {
// The user will not be counted into the experiment, but should see the reference variation
variationID = 0;
}
}
if (variationID == 0) {
//This is the default / reference number of products to display
recommendedProductsNumber = 5;
}
else if (variationID == 148382) {
//We are changing number of recommended products for this variation to 10
recommendedProductsNumber = 10;
}
else if (variationID == 187791) {
//We are changing number of recommended products for this variation to 8
recommendedProductsNumber = 8;
}
// Here you should have code to generate the HTML page back to the client, where recommendedProductsNumber will be used
}, function () {
console.log("Timeout occured in the JavaScript SDK initialization.");
}, 2000);
Running an A/B experiment on your JavaScript application means bucketing your visitors into several groups (one per variation). The SDK takes care of this bucketing (and the associated reporting) automatically.
Triggering an experiment by calling the triggerExperiment()
method will register a random variation for a given visitorCode. If this visitorCode is already associated with a variation (most likely a returning visitor that has already been exposed to the experiment previously), then it will return the previous variation assigned for the given experiment.
Implementing variation code
let recommendedProductsNumber;
if (variationID == 0) {
//This is the default / reference number of products to display
recommendedProductsNumber = 5;
}
else if (variationID.equals == 148382) {
//We are changing number of recommended products for this variation to 10
recommendedProductsNumber = 10;
}
else if (variationID == 187791) {
//We are changing number of recommended products for this variation to 8
recommendedProductsNumber = 8;
}
To execute different code paths depending on the variation assigned to the visitor, you will need the list of all the experiment's variation IDs. You can find these variation IDs (as well as the experiment ID) by opening the experiment in the back-office interface. By convention, the reference (original variation) always has an ID equal to 0.
Once you have the IDs of the different variations, you can implement a different action for each variation, and one of the code paths will be executed, based on the associated variationID for the current visitor. Generally, this can be done using a simple if / else or switch mechanism. In our example, we just change the number of recommended products with two different variations.
Tracking conversion
let visitorCode = kameleoonClient.getVisitorCode("example.com");
let goalID = 83023;
kameleoonClient.trackConversion(visitorCode, goalID);
After you are done triggering an experiment, the next step is usually to start tracking conversions. This is done to measure performance characteristics according to the goals that make sense for your business.
For this purpose, use the trackConversion()
method of the SDK as shown in the example. You need to pass the visitorCode and goalID parameters so we can correctly track conversions for this particular visitor.
Obtaining results
Once your implementation is in place on the server side (experiment triggering, variations handling, and conversion tracking), it is time to launch the experiment on the Kameleoon platform. You do this in the same way as for a front-end test. Basic operations such as starting, pausing and stopping the experiment work exactly the same way.
After the experiment is launched, the first results will be available on our standard results page in the back-office after a duration of 30 minutes. This is because (as is the case with front-end testing) visits are considered over after 30 minutes of inactivity. Inactivity in this context means the absence of calls sent to the Kameleoon back-end servers (such calls are made via triggerExperiment()
, trackConversion()
or flush()
methods).
Technical considerations
Kameleoon made an important architectural design decision with its SDK technology, namely that every SDK must comply with a zero latency policy. In practice, this means that any blocking remote server call should be banned, as even the fastest remote call would add a 20ms latency to your application. And if for any reason our servers are slower to reply than usual (unfortunately, this can happen), this delay can quickly increase to hundreds of milliseconds, seconds... or even completely block the run of your web-application for the end user. We believe that web performance is of paramount importance in today's world and we don't think adding A/B testing or feature flagging capabilities should come at the cost of a slow down in your web-application.
However, in the case of the JavaScript SDK, since it runs on users' devices, the configuration of all active experiments / feature flags has to be fetched at the start of the session. It cannot be fetched once for every visitor, similarly to the server-side case. This introduces a mandatory distant server call with an associated callback, which means code using the JS SDK (implementing experiments or feature flags) cannot be ran prior to the execution of this callback. For maximal performance, this can be avoided by using our Activation API
in tandem with a standard Kameleoon install, where the configuration data is directly embedded in the Kameleoon application file (ie, the JavaScript file contains both the engine code and the configuration of active experiments). But this is a completely different process (advantages of each method are highlighted here), with a different API and no npm package (installation is done by integrating a standard JS tag on the HTML source page). It is described on this article.
Apart from this initial remote call, we guarantee that the use of our SDKs has absolutely no performance impact. Variation allocation for experiments takes place directly on the SDK code (without any distant API call), and tracking calls are made asynchronously in a non-blocking way (in the background).
Having a zero latency policy also imposes some other constraints. The main one is that user data about your visitor should be kept locally, and not fetched from a remote server. For instance, if you set a custom data for a given visitor, we must store this somehow in the user's device. In the case of the JavaScript SDK, this is implemented via a map of visitor data directly on the browser LocalStorage. So if you use new KameleoonData.CustomData()
and then kameleoonClient.addData()
methods, the information will be stored in the browser's LocalStorage. It should usually not grow too big in size, unless you use an extremely large amount of custom data.
Overview
When you update your experiment or feature flag configuration, the SDK can get it in two different ways. The first - polling - consists in retrieving the configuration at regular intervals. The second - streaming - is to retrieve the new configuration immediately.
Polling
This mode of obtaining the configuration is used by default. The SDK will send a request to Cloudflare CDN at regular intervals to retrieve the configuration. If you have not set an interval in the SDK configuration, the configuration in SDK will be refreshed every 60 minutes. It can be configured with actions_configuration_refresh_interval parameter.
-
Benefits:
- When intervals are moderately spaced, this way of updating configuration consumes nominal memory and network resources.
Streaming
This mode allows the SDK to automatically take into account the new configuration without delay. When turned on, Kameleoon SDK is notified of any changes to the configuration in real-time, thanks to server-sent events (SSE).
-
Benefits:
- Makes it possible to propagate and apply a new configuration in real-time.
- Reduce network traffic compared to polling at short intervals, as streaming does not require sending periodic requests. It opens the connection once and then keeps it permanently open and ready to receive data.
If you rely on instant data updates (real-time), then streaming is for you. If you wish to activate this mode, please contact us.
Reference
This is a full reference documentation of the JavaScript SDK.
If this is your first time working with the JavaScript SDK, we strongly recommend you go over our Getting started tutorial to integrate the SDK and start experimenting in a few minutes.
KameleoonClient
KameleoonClient
let kameleoonClient = new KameleoonClient("a8st4f59bj");
kameleoonClient = new KameleoonClient("a8st4f59bj", false, {"actions_configuration_refresh_interval": 5});
The starting point for using the SDK is the initialization step. All interactions with the SDK are done through an object named KameleoonClient, therefore you need to create this object.
Arguments
Name | Type | Description |
siteCode | String | Code of the website you want to run experiments on. This unique code id can be found in our platform's back-office. This field is mandatory. |
configurationObject | Object | JSON object filled with configuration parameters. This field is optional, the default value being an empty object. |
getVisitorCode
const { v4: uuidv4 } = require("uuid");
let visitorCode = kameleoonClient.getVisitorCode("example.com");
visitorCode = kameleoonClient.getVisitorCode("example.com", visitorCode);
visitorCode = kameleoonClient.getVisitorCode("example.com", uuidv4());
The getVisitorCode()
helper method should be called to obtain the Kameleoon visitorCode for the current visitor. This is especially important when using Kameleoon in a mixed front-end and back-end environment, where user identification consistency must be guaranteed. The implementation logic is described here:
First we check if a kameleoonVisitorCode cookie can be found. If so, we will use this as the visitor identifier.
If no cookie is found, we either randomly generate a new identifier, or use the defaultVisitorCode argument as identifier if it is passed. This allows our customers to use their own identifiers as visitor codes, should they wish to. This can have the added benefit of matching Kameleoon visitors with their own users without any additional look-ups in a matching table.
In any case, the JavaScript kameleoonVisitorCode cookie is set with the value. Then this identifier value is finally returned by the method.
For more information, refer to this article.
Arguments
Name | Type | Description |
topLevelDomain | String | Your current top level domain for the concerned site (this information is needed to set the corresponding cookie accordingly, on the top level domain). This field is mandatory. |
defaultVisitorCode | String | This parameter will be used as the visitorCode if no existing kameleoonVisitorCode cookie is found on the request. This field is optional, and by default a random visitorCode will be generated. |
Return value
Type | Description |
String | A visitorCode that will be associated with this particular user and should be used with most of the methods of the SDK. |
triggerExperiment
let visitorCode = kameleoonClient.getVisitorCode("example.com");
let experimentID = 75253;
let variationID;
kameleoonClient.runWhenReady(function () {
let variationID;
try {
variationID = kameleoonClient.triggerExperiment(visitorCode, experimentID);
}
catch (e) {
if (e.type == KameleoonException.NotTargeted.type) {
// The user did not trigger the experiment, as the associated targeting segment conditions were not fulfilled. He should see the reference variation
variationID = 0;
}
if (e.type == KameleoonException.NotActivated.type) {
// The user triggered the experiment, but did not activate it. Usually, this happens because the user has been associated with excluded traffic
variationID = 0;
}
if (e.type == KameleoonException.ExperimentConfigurationNotFound.type) {
// The user will not be counted into the experiment, but should see the reference variation
variationID = 0;
}
}
}, function () {
console.log("Timeout occured in the JavaScript SDK initialization.");
}, 2000);
To trigger an experiment, call the triggerExperiment()
method of our SDK.
This method takes visitorCode and experimentID as mandatory arguments to register a variation for a given user.
If such a user has never been associated with any variation, the SDK returns a randomly selected variation. If a user with a given visitorCode is already registered with a variation, it will detect the previously registered variation and return the variationID.
You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.
Arguments
Name | Type | Description |
visitorCode | String | Unique identifier of the user. This field is mandatory. |
experimentID | Number | ID of the experiment you want to expose to a user. This field is mandatory. |
Return value
Name | Type | Description |
variationID | Number | ID of the variation that is registered for a given visitorCode. By convention, the reference (original variation) always has an ID equal to 0. |
Exceptions Thrown
Error Message | Description |
KameleoonException.NotTargeted | Exception indicating that the current visitor / user did not trigger the required targeting conditions for this experiment. The targeting conditions are defined via Kameleoon's segment builder. |
KameleoonException.NotActivated | Exception indicating that the current visitor / user triggered the experiment (met the targeting conditions), but did not activate it. The most common reason for that is that part of the traffic has been excluded from the experiment and should not be tracked. |
KameleoonException.ExperimentConfigurationNotFound | Exception indicating that the requested experiment ID has not been found in the internal configuration of the SDK. This is usually normal and means that the experiment has not yet been started on Kameleoon's side (but code triggering / implementing variations is already deployed on the web-application's side). |
activateFeature
let visitorCode = kameleoonClient.obtainVisitorCode("example.com");
let featureKey = "new_checkout";
let hasNewCheckout = false;
try {
hasNewCheckout = kameleoonClient.activateFeature(visitorCode, featureKey);
}
catch (e) {
if (e.type == KameleoonException.NotActivated.type) {
// The user did not trigger the feature, as the associated targeting segment conditions were not fulfilled. The feature should be considered inactive
hasNewCheckout = false;
}
if (e.type == KameleoonException.FeatureConfigurationNotFound.type) {
// The user will not be counted into the experiment, but should see the reference variation
hasNewCheckout = false;
}
}
if (hasNewCheckout)
{
// Implement new checkout code here
}
To activate a feature toggle, call the activateFeature()
method of our SDK.
This method takes a visitorCode and featureKey (or featureID) as mandatory arguments to check if the specified feature will be active for a given user.
If such a user has never been associated with this feature flag, the SDK returns a boolean value randomly (true if the user should have this feature or false if not). If a user with a given visitorCode is already registered with this feature flag, it will detect the previous featureFlag value.
You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.
Arguments
Name | Type | Description |
visitorCode | String | Unique identifier of the user. This field is mandatory. |
featureID or featureKey | Number or String | ID or Key of the feature you want to expose to a user. This field is mandatory. |
Return value
Type | Description |
Boolean | Value of the feature that is registered for a given visitorCode. |
Exceptions Thrown
Type | Description |
KameleoonException.NotTargeted | Exception indicating that the current visitor / user did not trigger the required targeting conditions for this feature. The targeting conditions are defined via Kameleoon's segment builder. |
KameleoonException.FeatureConfigurationNotFound | Exception indicating that the requested feature ID has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side). |
getFeatureVariable
const visitorCode = kameleoonClient.getVisitorCode("example.com");
const featureKey = "feature_key";
const variableName = "var"
try {
const variableValue = kameleoonClient.getFeatureVariable(visitorCode, featureKey, variableName);
// your custom code depending of variableValue
}
catch (e) {
if (e instanceof KameleoonException.FeatureConfigurationNotFound) {
// The error is happened, feature flag isn't found in current configuraiton
}
}
To get variable of variation key associated with a user, call the getFeatureVariable()
method of our SDK.
This method takes a visitorCode, featureKey and variableName as mandatory arguments to get a variable of variation key for a given user.
If such a user has never been associated with this feature flag, the SDK returns a variable value of variation key randomly (according to the feature flag rules). If a user with a given visitorCode is already registered with this feature flag, it will detect the variable value for previous associated variation. If the user does not match any of the rules, the variable of default value will be returned.
You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.
Arguments
Name | Type | Description |
visitorCode | string | Unique identifier of the user. This field is mandatory. |
featureKey | string | Key of the feature you want to expose to a user. This field is mandatory. |
variableName | string | Name of the variable you want to get a value. This field is mandatory. |
Return value
Type | Description |
any | Value of variable of variation that is registered for a given visitorCode for this feature flag. Possible types: boolean, number, string, json object |
Exceptions Thrown
Type | Description |
KameleoonException.FeatureConfigurationNotFound | Exception indicating that the requested feature key has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side). |
getFeatureAllVariables
let featureKey = "myFeature";
let data;
try {
data = kameleoonClient.getFeatureAllVariables(featureKey);
}
catch (e) {
if (e instanceof KameleoonException.FeatureConfigurationNotFound) {
// The feature is not yet activated on Kameleoon's side
}
}
To retrieve the all feature variables, call the getFeatureAllVariables()
method of our SDK. A feature variable can be changed easily via our web application.
This method takes one input parameter: featureKey. It will return the data with the object type, as defined on the web interface. It will throw an exception (KameleoonException.FeatureConfigurationNotFound
) if the requested feature has not been found in the internal configuration of the SDK.
Arguments
Name | Type | Description |
featureKey | string | Key of the feature you want to obtain to a user. This field is mandatory. |
Return value
Type | Description |
object | Data associated with this feature flag. The values of object can be a number, string, boolean or another object (depending on the type defined on the web interface). |
Exceptions Thrown
Type | Description |
KameleoonException.FeatureConfigurationNotFound | Exception indicating that the requested feature key has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side. |
getFeatureVariationKey
const visitorCode = kameleoonClient.getVisitorCode("example.com");
const featureKey = "feature_key";
let variationKey = ""
try {
variationKey = kameleoonClient.getFeatureVariationKey(visitorCode, featureKey);
}
catch (e) {
if (e instanceof KameleoonException.FeatureConfigurationNotFound) {
// The error is happened, feature flag isn't found in current configuraiton
}
}
switch(variationKey) {
case 'on':
// main variation key is selected for visitorCode
break;
case 'alternative_variation':
// alternative variation key
break;
default:
// default variation key
break;
}
To get feature variation key, call the getFeatureVariationKey()
method of our SDK.
This method takes a visitorCode and featureKey as mandatory arguments to get variation key for a given user.
If such a user has never been associated with this feature flag, the SDK returns a variation key randomly (according to the feature flag rules). If a user with a given visitorCode is already registered with this feature flag, it will detect the previous variation key value. If the user does not match any of the rules, the default value will be returned, which we can define in your customer's account.
You have to make sure that proper error handling is set up in your code as shown in the example to the right to catch potential exceptions.
Arguments
Name | Type | Description |
visitorCode | string | Unique identifier of the user. This field is mandatory. |
featureKey | string | Key of the feature you want to expose to a user. This field is mandatory. |
Return value
Type | Description |
string | Variation key of the feature flag that is registered for a given visitorCode. |
Exceptions Thrown
Type | Description |
KameleoonException.FeatureConfigurationNotFound | Exception indicating that the requested feature key has not been found in the internal configuration of the SDK. This is usually normal and means that the feature flag has not yet been activated on Kameleoon's side (but code implementing the feature is already deployed on the web-application's side). |
getVariationAssociatedData
let visitorCode = kameleoonClient.getVisitorCode("example.com");
int experimentID = 75253;
try {
let variationID = kameleoonClient.triggerExperiment(visitorCode, experimentID);
let jsonObject = kameleoonClient.getVariationAssociatedData(variationID);
let firstName = jsonObject["firstName"];
}
catch (e) {
if (e.type == KameleoonException.VariationConfigurationNotFound.type) {
// The variation is not yet activated on Kameleoon's side, ie the associated experiment is not online
}
}
To retrieve JSON data associated with a variation, call the getVariationAssociatedData()
method of our SDK. The JSON data usually represents some metadata of the variation, and can be configured on our web application interface or via our Automation API.
This method takes the variationID as a parameter and will return the data as a JavaScript object. It will throw an exception (KameleoonException.VariationConfigurationNotFound
) if the variation ID is wrong or corresponds to an experiment that is not yet online.
Arguments
Name | Type | Description |
variationID | int | ID of the variation you want to obtain associated data for. This field is mandatory. |
Return value
Type | Description |
Object | Data associated with this variationID. |
Exceptions Thrown
Type | Description |
KameleoonException.VariationConfigurationNotFound | Exception indicating that the requested variation ID has not been found in the internal configuration of the SDK. This is usually normal and means that the variation's corresponding experiment has not yet been activated on Kameleoon's side. |
trackConversion
let {KameleoonClient, KameleoonData, KameleoonException} = require("kameleoon-client-javascript");
let visitorCode = kameleoonClient.getVisitorCode("example.com");
let goalID = 83023;
kameleoonClient.addData(visitorCode, new KameleoonData.Browser(KameleoonData.browsers.CHROME));
kameleoonClient.addData(
visitorCode,
new KameleoonData.PageView("https://url.com", "title", [3]),
new KameleoonData.Interest(2)
);
kameleoonClient.addData(visitorCode, new KameleoonData.Conversion(32, 10, false));
kameleoonClient.trackConversion(visitorCode, goalID);
To track conversion, use the trackConversion()
method. This method requires visitorCode and goalID to track conversion on this particular goal. In addition, this method also accepts revenue as a third optional argument to track revenue. The visitorCode is usually identical to the one that was used when triggering the experiment.
The trackConversion()
method doesn't return any value. This method is non-blocking as the server call is made asynchronously.
Arguments
Name | Type | Description |
visitorCode | String | Unique identifier of the user. This field is mandatory. |
goalID | Number | ID of the goal. This field is mandatory. |
revenue | Number | Revenue of the conversion. This field is optional. |
addData
let {KameleoonClient, KameleoonData, KameleoonException} = require("kameleoon-client-javascript");
let visitorCode = kameleoonClient.getVisitorCode("example.com");
kameleoonClient.addData(visitorCode, new KameleoonData.Browser(KameleoonData.browsers.CHROME));
kameleoonClient.addData(
visitorCode,
new KameleoonData.PageView("https://url.com", "title", [3]),
new KameleoonData.Interest(0)
);
kameleoonClient.addData(visitorCode, new KameleoonData.Conversion(32, 10, false));
To associate various data with the current user, we can use the addData()
method. This method requires the visitorCode as a first parameter, and then accepts several additional parameters. These additional parameters represent the various Data Types allowed in Kameleoon.
Note that the addData()
method doesn't return any value and doesn't interact with the Kameleoon back-end servers by itself. Instead, all declared data is saved for further sending via the flush()
method described in the next paragraph. This reduces the number of server calls made, as data is usually grouped into a single server call triggered by the execution of flush()
.
Arguments
Name | Type | Description |
visitorCode | String | Unique identifier of the user. This field is mandatory. |
dataTypes | KameleoonData | Custom data types which may be passed separated by a comma. |
flush
let {KameleoonClient, KameleoonData, KameleoonException} = require("kameleoon-client-javascript");
let visitorCode = kameleoonClient.getVisitorCode("example.com");
kameleoonClient.addData(visitorCode, new KameleoonData.Browser(KameleoonData.browsers.CHROME));
kameleoonClient.addData(
visitorCode,
new KameleoonData.PageView("https://url.com", "title", [3]),
new KameleoonData.Interest(0)
);
kameleoonClient.addData(visitorCode, new KameleoonData.Conversion(32, 10, false));
kameleoonClient.flush(visitorCode);
Data associated with the current user via addData()
method is not immediately sent to the server. It is stored and accumulated until it is sent automatically by the triggerExperiment()
or trackConversion()
methods, or manually by the flush()
method. This allows the developer to control exactly when the data is flushed to our servers. For instance, if you call the addData()
method a dozen times, it would be a waste of ressources to send data to the server after each addData()
invocation. Just call flush()
once at the end.
The flush()
method doesn't return any value. This method is non-blocking as the server call is made asynchronously.
Arguments
Name | Type | Description |
visitorCode | String | Unique identifier of the user. This field is mandatory. |
getExperimentList
const experimentIds = kameleoonClient.getExperimentList()
Returns a list of experiment IDs currently available for the SDK
Return value
Type | Description |
Array | List of experiment's IDs |
getExperimentListForVisitorCode
const onlyActive = true
const experimentIds = kameleoonClient.getExperimentListForVisitorCode(visitorCode, onlyActive)
This method takes two input parameters: visitorCode and onlyActive. If onlyActive
parameter is true
result contains only active experiments, otherwise it contains all targeted experiments to specific visitorCode
. Returns a list of experiment IDs currently available for specific visitorCode
according to the onlyActive
option
Arguments
Name | Type | Description |
visitorCode | string | Unique identifier of the user. This field is mandatory. |
onlyActive | boolean | The value is true by default, result contains only active for the user experiments. Set false for fetching all targeted experiment IDs. This field is optional. |
Return value
Type | Description |
Array | List of experiment IDs available for specific visitorCode according to the onlyActive option |
getFeatureList
const featureFlagIds = kameleoonClient.getFeatureList()
Returns a list of feature flag keys currently available for the SDK
Return value
Type | Description |
Array | List of feature flag keys |
getFeatureListForVisitorCode
const onlyActive = true
const experimentIds = kameleoonClient.getFeatureListForVisitorCode(visitorCode, onlyActive)
This method takes two input parameters: visitorCode and onlyActive. If onlyActive
parameter is true
result contains only active feature flags, otherwise it contains all targeted feature flags to specific visitorCode
. Returns a list of feature flag IDs currently available for specific visitorCode
according to the onlyActive
option
Arguments
Name | Type | Description |
visitorCode | string | Unique identifier of the user. This field is mandatory. |
onlyActive | boolean | The value is true by default, result contains only active for the user feature flags. Set false for fetching all targeted feature flag IDs. This field is optional. |
Return value
Type | Description |
Array | List of feature flag keys available for specific visitorCode according to the onlyActive option |
retrieveDataFromRemoteSource
const data = await kameleoonClient.retrieveDataFromRemoteSource("test")
kameleoonClient.retrieveDataFromRemoteSource("test").then((data: any) => {
//operate with retrieveing data
})
The retrieveDataFromRemoteSource()
method allows you to retrieve data (according to a key passed as argument) for specified siteCode (specified in KameleoonClient
constructor) 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.
Arguments
Name | Type | Description |
key | String | The key that the data you try to get is associated with. This field is mandatory. |
Return value
Type | Description |
Promise | Promise with retrieving data for specific key |
onUpdateConfiguration
kameleoonClient.onUpdateConfiguration(async () => {
// configuration was updated
})
The onUpdateConfiguration()
method allows you to handle the event when configuration has updated data. It takes one input parameter handler. The handler that will be called when the configuration is updated using a real-time configuration event.
Arguments
Name | Type | Description |
handler | () => void | The handler that will be called when the configuration is updated using a real-time configuration event. |
KameleoonData
Browser
kameleoonClient.addData(visitorCode, new KameleoonData.Browser(KameleoonData.browsers.CHROME));
Name | Type | Description |
browser | Number | List of browsers: CHROME, INTERNET_EXPLORER, FIREFOX, SAFARI, OPERA, OTHER. This field is mandatory. |
PageView
kameleoonClient.addData(visitorCode, new KameleoonData.PageView('https://url.com', 'title', [3]));
Name | Type | Description |
url | String | URL of the page viewed. This field is mandatory. |
title | String | Title of the page viewed. This field is mandatory. |
referrers | Array | Referrers of viewed pages. This field is optional. |
Conversion
kameleoonClient.addData(visitorCode, new KameleoonData.Conversion(32, 10, false));
Name | Type | Description |
goalID | Number | ID of the goal. This field is mandatory. |
revenue | Number | Conversion revenue. This field is optional. |
negative | Boolean | Defines if the revenue is positive or negative. This field is optional. |
CustomData
kameleoonClient.addData(visitorCode, new KameleoonData.CustomData(1, 'some custom value'));
Name | Type | Description |
index | Number | Index / ID of the custom data to be stored. This field is mandatory. |
value | String | Value of the custom data to be stored. This field is mandatory. |
Device
kameleoonClient.addData(visitorCode, new Device(DeviceType.Desktop));
Name | Type | Description |
device | DeviceType | List of devices: Phone, Tablet, Desktop. This field is mandatory. |
UserAgent
kameleoonClient.addData(
visitorCode,
new KameleoonData.UserAgent("Your User Agent")
);
Name | Type | Description |
value | string | The User-Agent value that will be sent with tracking requests. This field is mandatory. |