Con el SDK de JavaScript de Kameleoon, puede ejecutar experimentos y activar feature flags. Integrar nuestro SDK en su aplicación web es sencillo y su huella (memoria y uso de red) es baja.
Primeros pasos: Para obtener ayuda para comenzar, consulte la guía del desarrollador.
Changelog: Encontrará información sobre la última versión del SDK de JavaScript / TypeScript en el changelog.
Métodos del SDK: Para la documentación de referencia completa del SDK de JavaScript, consulte la sección referencia.
Guía del desarrollador
Esta sección le ayudará a comenzar y le presentará algunos de los conceptos más avanzados.
Primeros pasos
Instalación
La herramienta de instalación de SDK de Kameleoon es el mejor método para instalar el SDK rápidamente. El instalador de SDK le ayuda a instalar el SDK de su elección, generar una muestra de código básica y configurar las dependencias externas si es necesario.
Para usar la herramienta de instalación del SDK, instálela y ejecútela globalmente:
npm install --global @kameleoon/sdk-installer
kameleoon-sdk
O ejecútela directamente con npx:
npx @kameleoon/sdk-installer
También puede inyectar el SDK de JavaScript en su aplicación como un único archivo mediante la etiqueta <script>. Después podrá acceder a todos los métodos del SDK usando el objeto global KameleoonSDK.Ejemplo:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My App</title>
<script src="https://static.kameleoon.com/kameleoonSDK-4.24.0.js"></script>
<script type="module" src="app.js"></script>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
const { KameleoonClient, CustomData } = KameleoonSDK;
Para utilizar siempre la última versión de un release mayor, utilice el siguiente script, donde 4 es la versión mayor actual:https://static.kameleoon.com/kameleoonSDK-4-latest.js
Para permanecer siempre en una versión específica, indique en su lugar el número de versión completo. Por ejemplo, para la versión 4.24.0, que es la versión más antigua disponible como script estático, utilice lo siguiente:https://static.kameleoon.com/kameleoonSDK-4.24.0.js
Las versiones pueden consultarse en la página de releases.Por defecto, el script estático utiliza el bundle optimizado del SDK, en el que los mensajes de log INFO y DEBUG se han eliminado para reducir el tamaño del bundle.Si usa KameleoonLogger.setLogLevel(LogLevel.DEBUG) o KameleoonLogger.setLogLevel(LogLevel.INFO), utilice en su lugar el script estático full.https://static.kameleoon.com/kameleoonSDK-4-latest-full.js
https://static.kameleoon.com/kameleoonSDK-4.24.0-full.js
Inicializar el cliente Kameleoon
A continuación se ofrece una guía paso a paso para configurar el SDK de JavaScript en su aplicación.
import {
Environment,
KameleoonClient,
SDKConfigurationType,
} from '@kameleoon/javascript-sdk';
// -- Optional configuration
const configuration: Partial<SDKConfigurationType> = {
updateInterval: 20,
environment: Environment.Production,
cookieDomain: '.example.com',
};
const client = new KameleoonClient({ siteCode: 'my_site_code', configuration });
// -- Waiting for the client initialization using `async/await`
async function init(): Promise<void> {
await client.initialize();
}
init();
// -- Waiting for the client initialization using `Promise.then()`
client
.initialize()
.then(() => {})
.catch((error) => {});
import { Environment, KameleoonClient } from '@kameleoon/javascript-sdk';
// -- Optional configuration
const configuration = {
updateInterval: 20,
environment: Environment.Production,
cookieDomain: '.example.com',
};
const client = new KameleoonClient({ siteCode: 'my_site_code', configuration });
// -- Waiting for the client initialization using `async/await`
async function init() {
await client.initialize();
}
init();
// -- Waiting for the client initialization using `Promise.then()`
client
.initialize()
.then(() => {})
.catch((error) => {});
Para comenzar, los desarrolladores deben crear un punto de entrada para el SDK de JavaScript creando una nueva instancia del cliente Kameleoon.
Use KameleoonClient para ejecutar experimentos de funcionalidades y obtener el estado de los feature flags y sus variaciones.
La inicialización de KameleoonClient se realiza de forma asíncrona para garantizar que la llamada a la API de Kameleoon haya sido correcta. Para la inicialización, utilice el método initialize(). Use async/await, Promise.then() o cualquier otro método para gestionar la inicialización asíncrona del cliente.
Argumentos
| Nombre | Tipo | Descripción |
|---|
| siteCode (obligatorio) | string | Esta es la clave única del proyecto de Kameleoon que está utilizando con el SDK. Este campo es obligatorio. |
| configuration (opcional) | Partial<SDKConfigurationType> | Configuración del cliente |
| externals (opcional) | ExternalsType | Implementación externa de las dependencias del SDK (Dependencias externas) |
| stubMode (opcional) | boolean | Cuando se establece en true, el cliente operará en modo stub y no realizará ninguna operación. En este modo, todas las llamadas a métodos no ejecutan acciones, lo que garantiza que no se produzcan acciones externas ni efectos secundarios. |
Parámetros de configuración
SDK Version 3
SDK Version 4
| Nombre | Tipo | Descripción | Valor por defecto |
|---|
| updateInterval (opcional) | number | Especifica el intervalo de actualización, en minutos, con el que el SDK obtiene la configuración de los experimentos y feature flags activos. El valor determina el tiempo máximo que se tarda en propagar los cambios, como la activación o desactivación de feature flags o el lanzamiento de experimentos, a sus servidores de producción. Si no se especifica, el intervalo predeterminado se establece en 60 minutos. Adicionalmente, ofrecemos un modo streaming que utiliza server-sent events (SSE) para enviar nuevas configuraciones al SDK automáticamente y aplicarlas en tiempo real, sin retrasos. | 60 |
| environment (opcional) | Environment | entorno del feature flag | Environment.Production |
| targetingDataCleanupInterval (opcional) | number | intervalo en minutos para la limpieza de los datos de segmentación; el valor mínimo es 1 minuto | undefined (no se realizará ninguna limpieza) |
| domain (opcional) | string | dominio al que pertenece la cookie. Obsoleto, utilice cookieDomain en su lugar | undefined |
| cookieDomain (opcional) | string | dominio al que pertenece la cookie. | undefined |
| networkDomain (opcional) | string | dominio personalizado que el SDK utiliza para todas las solicitudes de red salientes. Se utiliza habitualmente para proxy. El formato es second_level_domain.top_level_domain (por ejemplo, example.com). Si se especifica un formato no válido, el SDK utiliza el valor predeterminado de Kameleoon. | undefined |
| requestTimeout (opcional) | number | tiempo de espera en milisegundos para todas las solicitudes de red del SDK; si se supera el tiempo de espera, la solicitud fallará. | 10_000 (10 seconds) |
| trackingInterval (opcional) | number | Especifica el intervalo para las solicitudes de seguimiento en milisegundos. Todos los visitantes que fueron evaluados para algún feature flag o tenían datos asociados se incluyen en esta solicitud de seguimiento, que se realiza una vez por intervalo. El valor mínimo es 100 ms y el valor máximo es 1_000 ms | 1_000 (1 second) |
El parámetro domain está obsoleto y se eliminará en una versión futura. Utilice cookieDomain en su lugar.
| Nombre | Tipo | Descripción | Valor por defecto |
|---|
| updateInterval (opcional) | number | Especifica el intervalo de actualización, en minutos, con el que el SDK obtiene la configuración de los experimentos y feature flags activos. El valor determina el tiempo máximo que se tarda en propagar los cambios, como la activación o desactivación de feature flags o el lanzamiento de experimentos, a sus servidores de producción. Si no se especifica, el intervalo predeterminado se establece en 60 minutos. Adicionalmente, ofrecemos un modo streaming que utiliza server-sent events (SSE) para enviar nuevas configuraciones al SDK automáticamente y aplicarlas en tiempo real, sin retrasos. | 60 |
| environment (opcional) | Environment | string | entorno del feature flag | Environment.Production |
| targetingDataCleanupInterval (opcional) | number | intervalo en minutos para la limpieza de los datos de segmentación; el valor mínimo es 1 minuto | undefined (no se realizará ninguna limpieza) |
| cookieDomain (opcional) | string | dominio al que pertenece la cookie. | undefined |
| networkDomain (opcional) | string | dominio personalizado que el SDK utiliza para todas las solicitudes de red salientes. Se utiliza habitualmente para proxy. El formato es second_level_domain.top_level_domain (por ejemplo, example.com). Si se especifica un formato no válido, el SDK utiliza el valor predeterminado de Kameleoon. | undefined |
| requestTimeout (opcional) | number | tiempo de espera en milisegundos para todas las solicitudes de red del SDK; si se supera el tiempo de espera, la solicitud fallará inmediatamente | 10_000 (10 seconds) |
| trackingInterval (opcional) | number | Especifica el intervalo para las solicitudes de seguimiento en milisegundos. Todos los visitantes que fueron evaluados para algún feature flag o tenían datos asociados se incluyen en esta solicitud de seguimiento, que se realiza una vez por intervalo. El valor mínimo es 1_000 ms y el valor máximo es 5_000 ms | 1_000 (1 second) |
| defaultDataFile (opcional) | string | La funcionalidad defaultDataFile garantiza que el SDK de Kameleoon esté siempre READY al proporcionar una configuración de respaldo cuando no existe un archivo de datos en caché. Los desarrolladores pueden precargar una configuración válida obteniéndola desde https://sdk-config.kameleoon.eu/v3/<sitecode> y pasándola como defaultDataFile durante la inicialización. Cuando se proporciona un timestamp dateModified (en milisegundos) más reciente que la versión en caché, el SDK utilizará el datafile por defecto en lugar de la versión en caché. Si se omite dateModified, el datafile por defecto solo se aplica cuando no existe una versión en caché. Esto garantiza que el SDK siempre disponga de una configuración válida, ya sea por defecto, en caché o actualizada. | undefined |
Option 1 (Recommended): Use JSON.stringify()const dataFileJson = {"configuration":{"consentType":.....,
{"key":"show_car","type":"JSON","value":"{\"make\":\"Porsche\",\"model\":\"911\"}"}},
"dateModified":1752209266000};
const dataFileString = JSON.stringify(dataFileJson);
const configuration = {
updateInterval: 20,
defaultDataFile: dataFileString
};
Option 2: Raw JSON string (escape special characters)const configuration = {
updateInterval: 20,
defaultDataFile: `{"configuration":{"consentType":.....,
{"key":"show_car","type":"JSON","value":"{\\"make\\":\\"Porsche\\",\\"model\\":\\"911\\"}"},
"dateModified":1752209266000}`
};
No utilice varias instancias del cliente en una misma aplicación, ya que aún no es totalmente compatible. Varias instancias del cliente pueden hacer que la configuración en almacenamiento local se sobrescriba y provoquen errores.
Activar un feature flag
Asignar un identificador único a un usuario
To assign a unique ID to a user, you can use the getVisitorCode() method. If a código de visitante doesn’t exist (from the request headers cookie), the method generates a random unique ID or uses a defaultVisitorCode that you would have generated. The ID is then set in a response headers cookie.
If you are using Kameleoon in Hybrid mode, calling the getVisitorCode() method ensures that the unique ID (código de visitante) is shared between the application file engine.js (previously named, kameleoon.js) and the SDK.
Retrieving a flag configuration
To implement a feature flag in your code, you must first create the feature flag in your Kameleoon account.
To determine the status or variation of a feature flag for a specific user, you should use the getVariation() or isFeatureFlagActive() method to retrieve the configuration based on the featureKey.
The getVariation() method handles both simple feature flags with ON/OFF states and more complex flags with multiple variations. The method retrieves the appropriate variation for the user by checking the feature rules, assigning the variation, and returning it based on the featureKey and visitorCode.
The isFeatureFlagActive() method can be used if you want to retrieve the configuration of a simple feature flag that has only an ON or OFF state, as opposed to more complex feature flags with multiple variations or targeting options.
If your feature flag has associated variables (como por ejemplo specific behaviors tied to each variation) getVariation() also enables you to access the Variation object, which provides details about the assigned variation and its associated experiment. This method checks whether the user is targeted, finds the visitor’s assigned variation, and saves it to storage. When track=true, the SDK will send the exposure event to the specified experiment on the next solicitud de seguimiento, which is automatically triggered based on the SDK’s tracking_interval_millisecond. By default, this interval is set to 1000 milliseconds (1 second).
The getVariation() method allows you to control whether tracking is done. If track=false, no exposure events will be sent by the SDK. This is useful if you prefer not to track data through the SDK and instead rely on client-side tracking managed by the Kameleoon engine, for example. Adicionalmente, setting track=false is helpful when using the getVariations() method, where you might only need the variations for all flags without triggering any tracking events. If you want to know more about how tracking works, view this article
Adding data points to target a user or filter / breakdown visits in reports
To target a user, ensure you’ve added relevant data points to their profile before retrieving the feature variation or checking if the flag is active. Use the addData() method to add these data points to the user’s profile.
Para recuperar los puntos de datos recogidos en otros dispositivos o para acceder a los datos pasados del usuario (recogidos en el lado del cliente cuando se utiliza Kameleoon en modo híbrido), utilice el método getRemoteVisitorData(). This method asynchronously fetches data from the servers. It is important to call getRemoteVisitorData() before retrieving the variation or checking if the feature flag is active, as this data might be required to assign a user to a given variation.
To learn more about available targeting conditions, see the detailed article on the subject.
Adicionalmente, the data points you add to the visitor profile will be available when analyzing your experiments, allowing you to filter and break down your results by factors like device and browser. Kameleoon Hybrid mode automatically collects a variety of data points on the client-side, making it easy to break down your results based on these pre-collected data points. See the complete list here.
Si necesita rastrear puntos de datos adicionales más allá de lo que se recoge automáticamente, puede utilizar la funcionalidad Custom Data de Kameleoon. Custom Data le permite capturar y analizar información específica relevante para sus experimentos. No olvide llamar al método flush() para enviar los datos recogidos a los servidores de Kameleoon para su análisis.
To ensure your results are accurate, it’s recommended to filter out bots by using the UserAgent data type.
Tracking goal conversions
When a user completes a desired action (como por ejemplo making a purchase), it is recorded as a conversion. To track conversions, use the trackConversion() method and provide the required visitorCode and goalId parameters.
La solicitud de seguimiento de la conversión se enviará junto con la siguiente solicitud de seguimiento programada, que el SDK envía a intervalos regulares (definidos por tracking_interval_millisecond). If you prefer to send the request immediately, use the flush() method with the parameter instant=true.
Sending events to analytics solutions
To track conversions and send exposure events to your customer analytics solution, you must first implement Kameleoon in Hybrid mode. Then, use the getEngineTrackingCode() method.
The getEngineTrackingCode() method retrieves the unique tracking code required to send exposure events to your analytics solution. Using this method allows you to record events and send them to your desired analytics platform.
Uso de una clave de bucketing personalizada
By default, Kameleoon uses a unique, anonymous visitor ID (visitorCode) to assign users to feature flag variations. This ID is typically generated and stored on the user’s device (in a browser cookie for client-side and server-side SDKs—in persistent storage for mobile SDKs). Sin embargo, in certain scenarios you may need to ensure all users of the same organization see the same variant of a feature flag.
The Custom Bucketing Key option allows you to override this default behavior by providing your own custom identifier for bucketing. This override ensures that Kameleoon’s assignment logic uses your specified key instead of the default visitorCode.
Casos de uso
Using a custom bucketing key is essential for maintaining consistency and accuracy in your feature flag assignments, particularly in these situations:
- Experimentos a nivel de cuenta u organización: Para productos B2B o escenarios en los que desea asignar a todos los usuarios de la misma organización a la misma variación, puede utilizar un identificador como un
accountId. Las claves de bucketing personalizadas son fundamentales para realizar pruebas A/B de funcionalidades que afectan a todo un equipo o empresa.
Al implementar una clave de bucketing personalizada, garantiza una mayor consistencia y precisión en sus experimentos, lo que se traduce en resultados más fiables y una mejor experiencia de usuario.
Detalles técnicos
Cuando configura una clave de bucketing personalizada para un feature flag, proporciona a Kameleoon un identificador específico procedente de los datos de su aplicación:
client.addData(visitorCode, new CustomData(index, 'newVisitorCode'));
- Providing the custom key: You provide your custom identifier to the Kameleoon SDK using the
addData() method. In this method, you will pass your chosen custom bucketing key as a CustomData object. Here, newVisitorCode refers to the identifier you wish to use for your bucketing (for example, the new userId or accountId).
For the custom bucketing key to function correctly, it must also be defined and configured for the feature flag during the flag creation or editing process. Without this corresponding configuration, the SDK’s bucketing will not apply your custom key. For detailed instructions on how to set this up in Kameleoon, refer to this article.
- Bucketing logic: Once a custom bucketing key is provided through the
addData() method, all hash calculations for assigning users to variations will use this newVisitorCode (your custom key) instead of the default visitorCode. Using the newVisitorCode means that the bucketing decision is tied to your custom identifier, ensuring consistent assignments across various contexts where that identifier is present.
- Data tracking and analytics: It’s crucial to note that while the
newVisitorCode (your custom key) is used for bucketing decisions, all subsequent data (tracking events and conversions, for example) is sent and associated with the original visitorCode. This separation ensures that your analytics accurately reflect individual user journeys and interactions within your experiment’s broader context, even when bucketing is performed at a higher level (like an account) or across multiple devices/sessions. Your original datos del visitante remains intact for comprehensive reporting.
Requisitos técnicos
To effectively use a custom bucketing key:
- The key must be a
string.
- Debe ser única para la entidad que desea segmentar (por ejemplo, si utiliza un
userId, el ID de cada usuario debe ser único).
- La clave debe estar disponible para el SDK en el momento exacto en el que se evalúa la decisión del feature flag para ese usuario o solicitud.
Condiciones de segmentación
Los SDKs de Kameleoon admiten una variedad de condiciones de segmentación predefinidas que puede utilizar para segmentar usuarios en sus campañas.
Para ver la lista de condiciones admitidas por este SDK, consulte usar el historial de visitas para segmentar usuarios.
También puede utilizar sus propios datos externos para segmentar usuarios.
Registro de logs
The SDK generates logs to reflect various internal processes and issues.
Niveles de log
The SDK supports configuring limiting logging by a log level.
import { KameleoonClient, KameleoonLogger, LogLevel } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code', configuration });
// The `NONE` log level does not allow logging.
client.setLogLevel(LogLevel.NONE);
// Or use directly KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.NONE);
// The `ERROR` log level only allows logging issues that may affect the SDK's primary behavior.
client.setLogLevel(LogLevel.ERROR);
// Or use directly KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.ERROR);
// The `WARNING` log level allows logging issues which may require additional attention.
// It extends the `ERROR` log level.
// The `WARNING` log level is a default log level.
client.setLogLevel(LogLevel.WARNING);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.WARNING);
import { KameleoonClient, KameleoonLogger, LogLevel } from ‘@kameleoon/javascript-sdk/full’;
// The `INFO` log level allows logging general information on the SDK’s internal processes.
// It extends the `WARNING` log level.
client.setLogLevel(LogLevel.INFO);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.INFO);
// The `DEBUG` level logs additional details about the SDK’s internal processes and extends the `INFO` level
// with more granular. diagnostic output.
// This information is not intended for end-user interpretation but can be sent to our support team
// to assist with internal troubleshooting.
client.setLogLevel(LogLevel.DEBUG);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.DEBUG);
import { KameleoonClient, KameleoonLogger, LogLevel } from ‘@kameleoon/javascript-sdk’;
const client = new KameleoonClient({ siteCode: ‘my_site_code’, configuration });
// The `NONE` log level does not allow logging.
client.setLogLevel(LogLevel.NONE);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.NONE);
// The `ERROR` log level only allows logging issues that may affect the SDK’s primary behavior.
client.setLogLevel(LogLevel.ERROR);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.ERROR);
// The `WARNING` log level allows logging issues which may require additional attention.
// It extends the `ERROR` log level.
// The `WARNING` log level is a default log level.
client.setLogLevel(LogLevel.WARNING);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.WARNING);
import { KameleoonClient, KameleoonLogger, LogLevel } from ‘@kameleoon/javascript-sdk’;
// The `INFO` log level allows logging general information on the SDK’s internal processes.
// It extends the `WARNING` log level.
client.setLogLevel(LogLevel.INFO);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.INFO);
// The `DEBUG` level logs additional details about the SDK’s internal processes and extends the `INFO` level
// with more granular. diagnostic output.
// This information is not intended for end-user interpretation but can be sent to our support team
// to assist with internal troubleshooting.
client.setLogLevel(LogLevel.DEBUG);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.DEBUG);
Gestión personalizada de los logs
El SDK escribe sus logs en la salida de consola de forma predeterminada. Este comportamiento puede modificarse.
La limitación de los logs por nivel de log se realiza de forma independiente a la lógica de gestión de los logs.
import { KameleoonClient, KameleoonLogger, IExternalLogger, LogLevel } from '@kameleoon/javascript-sdk';
export class CustomLogger implements IExternalLogger {
// `log` method accepts logs from the SDK
public log(level: LogLevel, message: string): void {
// Custom log handling logic here. For example:
switch (level) {
case LogLevel.DEBUG:
console.debug(message);
break;
case LogLevel.INFO:
console.info(message);
break;
case LogLevel.WARNING:
console.warn(message);
break;
case LogLevel.ERROR:
console.error(message);
break;
}
}
}
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
logger: new CustomLogger(),
},
});
// Log level filtering is applied separately from log handling logic.
// The custom logger will only accept logs that meet or exceed the specified log level.
// Ensure the log level is set correctly.
client.setLogLevel(LogLevel.DEBUG);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.DEBUG);
import { KameleoonClient, KameleoonLogger, LogLevel } from '@kameleoon/javascript-sdk';
export class CustomLogger {
// `log` method accepts logs from the SDK
log(level, message) {
// Custom log handling logic here. For example:
switch (level) {
case 'DEBUG':
console.debug(message);
break;
case 'INFO':
console.info(message);
break;
case 'WARNING':
console.warn(message);
break;
case 'ERROR':
console.error(message);
break;
}
}
}
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
logger: new CustomLogger(),
},
});
// Log level filtering is applied separately from log handling logic.
// The custom logger will only accept logs that meet or exceed the specified log level.
// Ensure the log level is set correctly.
client.setLogLevel(LogLevel.DEBUG);
// Or use KameleoonLogger
KameleoonLogger.setLogLevel(LogLevel.DEBUG);
Debe proporcionar un dominio como domain en la configuración de KameleoonClient, que se utilizará para almacenar el código de visitante de Kameleoon en cookies. Los dominios son importantes al trabajar con los métodos getVisitorCode y setLegalConsent. El dominio que proporcione se almacena en la cookie como la clave Domain=.
Configurar el dominio
El dominio que proporcione indica si la URL puede utilizar la cookie. Por ejemplo, si su dominio es www.example.com, la cookie solo está disponible desde una URL www.example.com. Esto significa que las páginas con el dominio app.example.com no pueden utilizar la cookie.
Para una mayor flexibilidad con los subdominios, puede especificar el dominio con un punto (.). Por ejemplo, el dominio .example.com permite que la cookie funcione tanto en app.example.com como en login.example.com.
No puede utilizar expresiones regulares, símbolos especiales, protocolo ni números de puerto en domain.
Adicionalmente, una lista específica de subdominios no puede utilizarse con el prefijo ..
A continuación se ofrece una pequeña hoja de referencia para dominios:
| Domain | Allowed URLs | Disallowed URLs |
|---|
www.example.com | ✅www.example.com | ❌ app.example.com |
| ✅ example.com | ❌ .com |
| | |
.example.com = example.com | ✅ example.com | ❌ otherexample.com |
| ✅ www.example.com | |
| ✅ app.example.com | |
| ✅ login.example.com | |
https://www.example.com | ⛔ bad domain | ⛔ bad domain |
www.example.com:4408 | ⛔ bad domain | ⛔ bad domain |
.localhost.com = localhost | ⛔ bad domain | ⛔ bad domain |
Desarrollo en localhost
localhost siempre se considera un dominio no válido, lo que dificulta probar el dominio al desarrollar en localhost.
There are two ways to avoid this issue:
- Don’t specify the
domain field in the SDK client while testing.
- Create a local domain for
localhost. Por ejemplo:
- Navigate to
/etc/hosts on Linux or to c:\Windows\System32\Drivers\etc\hosts on Windows.
- Open
hosts with file super user or administrator rights.
- Añadir un dominio al puerto
localhost, por ejemplo: 127.0.0.1 app.com
- Now you can run your app locally on
app.com:{my_port} and specify .app.com as your domain
Dependencias externas
Las dependencias externas del SDK utilizan el patrón dependency injection para darle la posibilidad de proporcionar sus propias implementaciones para ciertas partes de un SDK.
En el SDK de JavaScript, todas las dependencias externas tienen implementaciones predeterminadas que utilizan una API nativa del navegador, por lo que no es necesario proporcionarlas a menos que se requiera otra API para casos de uso específicos.
Here’s the list of available external dependencies:
| Dependency | Interface | Required/Optional | API Used | Descripción |
|---|
storage | IExternalStorage | Optional | Browser localStorage | Used for storing all the existing and collected SDK data. |
requester | IExternalRequester | Optional | Browser fetch | Used for performing all network requests. |
eventSource | IExternalEventSource | Optional | Browser EventSource | Used for receiving Server Sent Events for Real Time Update capabilities. |
visitorCodeManager | IExternalVisitorCodeManager | Optional | Browser cookie | Used for storing and synchronizing códigos de visitante. |
logger | ILogger | Optional | Custom implementation | Used for custom handling of logs from the SDK. Lets you define how logs are processed and their output. |
Lo siguiente example implements external dependencies. To import an interface from an SDK, create a class that implements the interface and pass the instantiated class to the SDK.
Almacenamiento
import { IExternalStorage, KameleoonClient } from '@kameleoon/javascript-sdk';
// --- External Storage implementation ---
// - JavaScript `Map` is used as an example storage
const storage = new Map();
class MyStorage<T> implements IExternalStorage<T> {
public read(key: string): T | null {
// - Read data using `key`
const data = storage.get(key);
// - Return `null` if there's no data
if (!data) {
return null;
}
// - Return obtained data
return data;
}
public write(key: string, data: T): void {
// - Write data using `key`
storage.set(key, data);
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
storage: new MyStorage(),
},
});
import { KameleoonClient } from '@kameleoon/javascript-sdk';
// --- External Storage implementation ---
// - JavaScript `Map` is used as an example storage
const storage = new Map();
class MyStorage {
read(key) {
// - Read data using `key`
const data = storage.get(key);
// - Return `null` if there's no data
if (!data) {
return null;
}
// - Return obtained data
return data;
}
write(key, data) {
// - Write data using `key`
storage.set(key, data);
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
storage: new MyStorage(),
},
});
EventSource
import {
IExternalEventSource,
KameleoonClient,
EventSourceOpenParametersType,
} from '@kameleoon/javascript-sdk';
// --- External EventSource implementation ---
// - Example uses native browser `EventSource`
class MyEventSource implements IExternalEventSource {
private eventSource?: EventSource;
public open({
eventType,
onEvent,
url,
}: EventSourceOpenParametersType): void {
// - Initialize `EventSource`
const eventSource = new EventSource(url);
this.eventSource = eventSource;
// - Add event listener with provided event type and event callback
this.eventSource.addEventListener(eventType, onEvent);
}
public close(): void {
// - Cleanup open event source
if (this.eventSource) {
this.eventSource.close();
}
}
public onError(callback: (error: Event) => void): void {
// - Set error callback
if (this.eventSource) {
this.eventSource.onerror = callback;
}
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
eventSource: new MyEventSource(),
},
});
import { KameleoonClient } from '@kameleoon/javascript-sdk';
// --- External EventSource implementation ---
// - Example uses native browser `EventSource`
class MyEventSource {
eventSource;
open({ eventType, onEvent, url }) {
// - Initialize `EventSource`
const eventSource = new EventSource(url);
this.eventSource = eventSource;
// - Add event listener with provided event type and event callback
this.eventSource.addEventListener(eventType, onEvent);
}
close() {
// - Cleanup open event source
if (this.eventSource) {
this.eventSource.close();
}
}
public onError(callback) {
// - Set error callback
if (this.eventSource) {
this.eventSource.onerror = callback;
}
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
eventSource: new MyEventSource(),
},
});
VisitorCodeManager
import {
IExternalVisitorCodeManager,
SetDataParametersType,
KameleoonClient,
KameleoonUtils,
} from '@kameleoon/javascript-sdk';
// --- External Visitor Code Manager implementation ---
// - Example uses browser `document.cookie` API
class MyVisitorCodeManager implements IExternalVisitorCodeManager {
public getData(key: string): string | null {
const cookieString = document.cookie;
// - Return `null` if no cookie was found
if (!cookieString) {
return null;
}
// - Parse cookie using the provided `key`
return KameleoonUtils.getCookieValue(cookieString, key);
}
public setData({
visitorCode,
domain,
maxAge,
key,
path,
}: SetDataParametersType): void {
// - Set cookie with provided parameters
let resultCookie = `${key}=${visitorCode}; Max-Age=${maxAge}; Path=${path}`;
if (domain) {
resultCookie += `; Domain=${domain}`;
}
document.cookie = resultCookie;
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
visitorCodeManager: new MyVisitorCodeManager(),
},
});
import { KameleoonClient, KameleoonUtils } from '@kameleoon/javascript-sdk';
// --- External Visitor Code Manager implementation ---
// - Example uses browser `document.cookie` API
class MyVisitorCodeManager {
getData(key) {
const cookieString = document.cookie;
// - Return `null` if no cookie was found
if (!cookieString) {
return null;
}
// - Parse cookie using provided `key`
return KameleoonUtils.getCookieValue(cookieString, key);
}
setData({ visitorCode, domain, maxAge, key, path }) {
// - Set cookie with provided parameters
let resultCookie = `${key}=${visitorCode}; Max-Age=${maxAge}; Path=${path}`;
if (domain) {
resultCookie += `; Domain=${domain}`;
}
document.cookie = resultCookie;
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
visitorCodeManager: new MyVisitorCodeManager(),
},
});
Requester
import {
RequestType,
IExternalRequester,
KameleoonResponseType,
SendRequestParametersType,
KameleoonClient,
} from '@kameleoon/javascript-sdk';
// --- External Requester Implementation
export class MyRequester implements IExternalRequester {
public async sendRequest({
url,
parameters,
}: SendRequestParametersType<RequestType>): Promise<KameleoonResponseType> {
// - Using native browser `fetch`
return await fetch(url, parameters);
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
requester: new MyRequester(),
},
});
import { KameleoonClient } from '@kameleoon/javascript-sdk';
// --- External Requester Implementation
export class MyRequester {
async sendRequest({ url, parameters }) {
// - Using native browser `fetch`
return await fetch(url, parameters);
}
}
// --- Create KameleoonClient ---
const client = new KameleoonClient({
siteCode: 'my_site_code',
externals: {
requester: new MyRequester(),
},
});
Gestión de errores
Almost every KameleoonClient method may throw an error occassionaly. These errors are deliberately predefined KameleoonErrors
that extend the native JavaScript Error class, providing useful messages and special type fields with a type KameleoonException.
KameleoonException is an enum containing all possible error types.
Para saber exactamente qué tipo de KameleoonException puede lanzar el método, consulte la sección Throws en la descripción del método de esta página, o pase el ratón sobre el método en su IDE para ver la descripción jsdocs.
Handling errors makes your application more stable and avoids technical issues.
import {
KameleoonError,
KameleoonClient,
KameleoonException,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
try {
await client.initialize();
const customData = new CustomData(0, 'my_data');
client.addData(visitorCode, customData);
} catch (error) {
// -- Type guard for inferring error type, as native JavaScript `catch`
// only infers `unknown`
if (error instanceof KameleoonError) {
switch (error.type) {
case KameleoonException.VisitorCodeMaxLength:
// -- Handle an error
break;
case KameleoonException.StorageWrite:
// -- Handle an error
break;
case KameleoonException.Initialization:
// -- Handle an error
break;
default:
break;
}
}
}
}
init();
import { KameleoonClient, KameleoonException } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
try {
await client.initialize();
const customData = new CustomData(0, 'my_data');
client.addData(visitorCode, customData);
} catch (error) {
switch (error.type) {
case KameleoonException.VisitorCodeMaxLength:
// -- Handle an error
break;
case KameleoonException.StorageWrite:
// -- Handle an error
break;
case KameleoonException.Initialization:
// -- Handle an error
break;
default:
break;
}
}
}
init();
Experimentación entre dispositivos
To support visitors who access an app from multiple devices, Kameleoon allows the synchronization of previously collected datos del visitante across each of the visitor’s devices and reconciliation of their visit history across devices through cross-device experimentation. Case studies and detailed information on how Kameleoon handles data across devices are available in the article on cross-device experimentation.
Sincronización de datos personalizados entre dispositivos
Aunque se utiliza la sincronización con mapeo personalizado para alinear los datos del visitante entre dispositivos, no siempre es necesaria. A continuación se presentan dos escenarios en los que no se requiere la sincronización con mapeo personalizado:
Same user ID across devices
If the same user ID is used consistently across all devices, synchronization is handled automatically without a custom mapping sync. It is enough to call the getRemoteVisitorData() method when you want to sync the data collected between multiple devices.
Multi-server instances with consistent IDs
In complex setups involving multiple servers (for example, distributed server instances), where the same user ID is available across servers, synchronization between servers (with getRemoteVisitorData()) is sufficient without additional custom mapping sync.
Customers who need additional data can refer to the getRemoteVisitorData() method description for further guidance. In the below code, it is assumed that the same unique identifier (in this case, the visitorCode, which can also be referred to as userId) is used consistently between the two devices for accurate data retrieval.
Si desea sincronizar los datos recogidos en tiempo real, debe elegir el ámbito Visitor para sus datos personalizados.
import { KameleoonClient, CustomData } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Custom Data with index `0` was set to `Visitor` scope
// in Kameleoon.
const customDataIndex = 0;
const customData = new CustomData(customDataIndex, 'my_data');
client.addData('my_visitor', customData);
client.flush();
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Before working with data, make `getRemoteVisitorData` call
await getRemoteVisitorData({ visitorCode: 'my_visitor_code' });
// -- New SDK code will have access to CustomData with `Visitor` scope
// defined on Device One.
// So, "my_data" is now available for targeting and tracking "my_visitor".
}
init();
import { KameleoonClient, CustomData } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Custom Data with index `0` was set to `Visitor` scope
// in Kameleoon.
const customDataIndex = 0;
const customData = new CustomData(customDataIndex, 'my_data');
client.addData('my_visitor', customData);
client.flush();
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Before working with data, make `getRemoteVisitorData` call.
await getRemoteVisitorData({ visitorCode: 'my_visitor_code' });
// -- New SDK code will have access to CustomData with `Visitor` scope
// defined on Device One.
// So, "my_data" is now available for targeting and tracking "my_visitor"
}
init();
Uso de datos personalizados para la fusión de sesiones
SDK Version 3
SDK Version 4
Cross-device experimentation allows you to combine a visitor’s history across each of their devices (history reconciliation). History reconciliation lets you merge different visitors sessions into a single session. To reconcile visit history, use CustomData to provide a unique identifier for the visitor.Follow the activating cross-device history reconciliation guide to set up your datos personalizados in Kameleoon.When your datos personalizados is set up, you can use it in your code to merge a visitor’s sessions. Sessions with the same identifier will always see the same experiment variation, and are displayed as a single visitor in the Visitor view of your experiment’s result page.La configuración del SDK garantiza que las sesiones asociadas siempre vean la misma variación del experimento.Después, puede utilizar el SDK normalmente. Los siguientes métodos pueden resultarle útiles para la fusión de sesiones:
getRemoteVisitorData with isUniqueIdentifier=true - to retrieve data for all linked visitors
trackConversion or flush with isUniqueIdentifier=true - to track data for a specific visitor that is associated with another visitor.
Here’s an example of how to use datos personalizados for session merging.En este ejemplo, we have an application with a login page. Since we don’t know the user ID at the moment of login, we use an anonymous visitor identifier generated by thegetVisitorCode method. After the user logs in, we can associate the anonymous visitor with the user ID and use it as the visitor’s unique identifier.import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
});
async function init(): Promise<void> {
await client.initialize();
const anonymousVisitor = getVisitorCode();
// -- Saving `visitorCode` in `window` to re-use it later
window.anonymousVisitor = anonymousVisitor;
// -- Getting a variation—assume it's variation `A`
const variation = client.getVariation({
visitorCode: anonymousVisitor,
featureKey: 'my_feature_key',
});
}
init();
import { CustomData } from '@kameleoon/javascript-sdk';
async function init(): Promise<void> {
// -- At this point, the anonymous visitor has logged in,
// and we have a user ID to use as a visitor identifier.
// -- Associating both visitors with an identifier Custom Data,
// where index `1` is the Custom Data's index, configured
// as a unique identifier in Kameleoon.
const userIdentifierData = new CustomData(1, 'my_user_id');
// -- Taking `visitorCode` from `window` object
client.addData(window.anonymousVisitor, userIdentifierData);
// -- Retrieving the variation for the user ID ensures
// consistency with the anonymous visitor's variation.
// Both the anonymous visitor and the user ID will be
// assigned variation `A`.
const variation = client.getVariation({
visitorCode: 'my_user_id',
featureKey: 'my_feature_key',
});
// -- `my_user_id` and `anonymousVisitor` are now linked.
// They can be tracked as a single visitor.
client.trackConversion({
visitorCode: 'my_user_id',
goalId: 123,
revenue: 100,
// -- Informing the SDK that the visitor is a unique identifier
isUniqueIdentifier: true,
});
// -- Additionally, linked visitors share previously
// collected remote data
const data = await client.getRemoteVisitorData({
visitorCode: 'my_user_id',
// -- Informing the SDK that the visitor is a unique identifier
isUniqueIdentifier: true,
});
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
});
async function init() {
await client.initialize();
const anonymousVisitor = getVisitorCode();
// -- Saving `visitorCode` in `window` to re-use it later.
window.anonymousVisitor = anonymousVisitor;
// -- Getting a variation—assume it's variation `A`
const variation = client.getVariation({
visitorCode: anonymousVisitor,
featureKey: 'my_feature_key',
});
}
init();
import { CustomData } from '@kameleoon/javascript-sdk';
async function init() {
// -- At this point anonymous visitor has logged in,
// and we have a user ID to use as a visitor identifier
// -- Associating both visitors with an identifier Custom Data,
// where index `1` is the Custom Data's index, configured
// as a unique identifier in Kameleoon.
const userIdentifierData = new CustomData(1, 'my_user_id');
// -- Taking `visitorCode` from `window` object
client.addData(window.anonymousVisitor, userIdentifierData);
// -- Retrieving the variation for the user ID ensures
// consistency with the anonymous visitor's variation.
// Both the anonymous visitor and the user ID will be
// assigned variation `A`.
const variation = client.getVariation({
visitorCode: 'my_user_id',
featureKey: 'my_feature_key',
});
// -- `my_user_id` and `anonymousVisitor` are now linked.
// They can be tracked as a single visitor.
client.trackConversion({
visitorCode: 'my_user_id',
goalId: 123,
revenue: 100,
// -- Informing the SDK that the visitor is a unique identifier.
isUniqueIdentifier: true,
});
// -- Additionally, linked visitors share previously
// collected remote data.
const data = await client.getRemoteVisitorData({
visitorCode: 'my_user_id',
// -- Informing the SDK that the visitor is a unique identifier.
isUniqueIdentifier: true,
});
}
init();
Cross-device experimentation allows for combining a visitor’s history across each of their devices (history reconciliation). History reconciliation allow merging different visitor sessions into one. To reconcile visit history, use CustomData to provide a unique identifier for the visitor. Para más información, see the dedicated documentation.After cross-device reconciliation is enabled, calling getRemoteVisitorData() with the parameter userId retrieves all known data for a given user.Sessions with the same identifier will always be shown the same variation in an experiment. In the Visitor view of your experiment’s results pages, these sessions will appear as a single visitor.La configuración del SDK garantiza que las sesiones asociadas siempre vean la misma variación del experimento. Sin embargo, there are some limitations regarding cross-device variation allocation. These limitations are outlined here.Follow the activating cross-device history reconciliation guide to set up your datos personalizados on the Kameleoon platform.Afterwards, you can use the SDK normally. Lo siguiente methods that may be helpful in the context of session merging:
getRemoteVisitorData() with added UniqueIdentifier(true) - to retrieve data for all linked visitors.
trackConversion() or flush() with added UniqueIdentifier(true) data - to track some data for specific visitor that is associated with another visitor.
Here’s an example of how to use datos personalizados for session merging.import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
});
async function init(): Promise<void> {
await client.initialize();
const anonymousVisitor = getVisitorCode();
// -- Saving `visitorCode` in `window` to re-use it later.
window.anonymousVisitor = anonymousVisitor;
// -- Getting a variation, assume it's variation `A`
const variation = client.getVariation({
visitorCode: anonymousVisitor,
featureKey: 'my_feature_key',
});
}
init();
import { CustomData, UniqueIdentifier } from '@kameleoon/javascript-sdk';
async function init(): Promise<void> {
// -- At this point anonymous visitor has logged in,
// and we have a user ID to use as a visitor identifier
// -- Associating both visitors with an identifier Custom Data,
// where index `1` is the Custom Data's index, configured
// as a unique identifier in Kameleoon.
const userIdentifierData = new CustomData(1, 'my_user_id');
// -- Taking `visitorCode` from `window` object
client.addData(window.anonymousVisitor, userIdentifierData);
// -- Flushing data for the anonymous `visitorCode`
client.flush(window.anonymousVisitor);
// -- Informing the SDK that the visitor is a unique identifier
client.addData('my_user_id', new UniqueIdentifier(true));
// -- Retrieving the variation for the user ID ensures
// consistency with the anonymous visitor's variation.
// Both the anonymous visitor and the user ID will be
// assigned variation `A`.
const variation = client.getVariation({
visitorCode: 'my_user_id',
featureKey: 'my_feature_key',
});
// -- `my_user_id` and `anonymousVisitor` are now linked.
// They can be tracked as a single visitor.
client.trackConversion({
visitorCode: 'my_user_id',
goalId: 123,
revenue: 100,
});
// -- Additionally, linked visitors share previously
// collected remote data.
const data = await client.getRemoteVisitorData({
visitorCode: 'my_user_id',
});
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
});
async function init() {
await client.initialize();
const anonymousVisitor = getVisitorCode();
// -- Saving `visitorCode` in `window` to re-use it later.
window.anonymousVisitor = anonymousVisitor;
// -- Getting a variation, assume it's variation `A`
const variation = client.getVariation({
visitorCode: anonymousVisitor,
featureKey: 'my_feature_key',
});
}
init();
import { CustomData, UniqueIdentifier } from '@kameleoon/javascript-sdk';
async function init() {
// -- At this point anonymous visitor has logged in,
// and we have a user ID to use as a visitor identifier
// -- Associating both visitors with an identifier Custom Data,
// where index `1` is the Custom Data's index, configured
// as a unique identifier in Kameleoon.
const userIdentifierData = new CustomData(1, 'my_user_id');
// -- Taking `visitorCode` from `window` object
client.addData(window.anonymousVisitor, userIdentifierData);
// -- Flushing data for the anonymous `visitorCode`
client.flush(window.anonymousVisitor);
// -- Informing the SDK that the visitor is a unique identifier.
client.addData('my_user_id', new UniqueIdentifier(true));
// -- Retrieving the variation for the user ID ensures
// consistency with the anonymous visitor's variation.
// Both the anonymous visitor and the user ID will be
// assigned variation `A`.
const variation = client.getVariation({
visitorCode: 'my_user_id',
featureKey: 'my_feature_key',
});
// -- `my_user_id` and `anonymousVisitor` are now linked.
// They can be tracked as a single visitor.
client.trackConversion({
visitorCode: 'my_user_id',
goalId: 123,
revenue: 100,
});
// -- Additionally, linked visitors share previously
// collected remote data.
const data = await client.getRemoteVisitorData({
visitorCode: 'my_user_id',
});
}
init();
Utilidades
The SDK has a set of utility methods that you can use to simplify your development process. All methods are represented as static members of KameleoonUtils class.
simulateSuccessRequest
Use the simulateSuccessRequest method to simulate a successful request to the Kameleoon server. It can be useful for custom Requester implementations, when a developer needs to simulate a successful request (for example, disabling tracking).
import {
KameleoonUtils,
IExternalRequester,
SendRequestParametersType,
RequestType,
KameleoonResponseType,
} from '@kameleoon/javascript-sdk';
// - Example of `Requester` with disabled tracking
class Requester implements IExternalRequester {
public async sendRequest({
url,
parameters,
requestType,
}: SendRequestParametersType<RequestType>): Promise<KameleoonResponseType> {
if (requestType === RequestType.Tracking) {
return KameleoonUtils.simulateSuccessRequest<RequestType.Tracking>(
requestType,
null,
);
}
return await fetch(url, parameters);
}
}
import { KameleoonUtils } from '@kameleoon/javascript-sdk';
// - Example of `Requester` with disabled tracking
class Requester {
async sendRequest({ url, parameters, requestType }) {
if (requestType === RequestType.Tracking) {
return KameleoonUtils.simulateSuccessRequest(requestType, null);
}
return await fetch(url, parameters);
}
}
Argumentos
| Nombre | Tipo | Descripción |
|---|
| requestType (obligatorio) | RequestType | A type of request |
| data (obligatorio) | SimulateRequestDataType[RequestType] | A type of request data, which is different depending on RequestType |
Data type SimulateRequestDataType is defined de la siguiente manera:
RequestType.Tracking - null
RequestType.ClientConfiguration - ClientConfigurationDataType
RequestType.RemoteData - JSONType
Return value
| Tipo | Descripción |
|---|
Promise<KameleoonResponseType> | returns a promise with the response of the request |
getCookieValue
Use the getCookieValue method to parse a common cookie string (key_1=value_1; key_2=value_2; ...) and get the value of a specific cookie key. This method is useful when working with a custom implementation of VisitorCodeManager.
import { KameleoonUtils } from '@kameleoon/javascript-sdk';
const cookies = 'key_1=value_1; key_2=value_2';
const key = 'key_1';
const value = KameleoonUtils.getCookieValue(cookies, key); // = `value_1`
import { KameleoonUtils } from '@kameleoon/javascript-sdk';
const cookies = 'key_1=value_1; key_2=value_2';
const key = 'key_1';
const value = KameleoonUtils.getCookieValue(cookies, key); // = `value_1`
Argumentos
| Nombre | Tipo | Descripción |
|---|
| cookie (obligatorio) | string | Cookie string in a form key_1=value_1; key_2=value_2 |
| key (obligatorio) | string | String representation of a key to find a value by |
Return value
| Tipo | Descripción | |
|---|
| `string | null` | returns a string with a cookie value or null if the key was not found |
Referencia
This is the full reference documentation for the Kameleoon JavaScript SDK.
Inicialización
initialize()
SDK Version 3
SDK Version 4
initialize() is an asynchronous method for KameleoonClient initialization. The method fetches Kameleoon SDK data from our servers or retrieves data from a local source if data is up-to-date or the update interval has not been reached.
-
If the SDK configuration could not be retrieved but there is an older configuration available in the SDK storage, the SDK uses the older configuration as a fallback and
initialize does not throw an error.
-
Client initialization has an optional offline mode.
It is activated by setting the optional
useCache parameter to true.
In offline mode, if solicitudes de seguimiento for any of lo siguiente methods fail due to internet connectivity issues, the SDK automatically resends the request when internet connection has been reestablished:import {
KameleoonClient,
KameleoonError,
KameleoonException,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
try {
await client.initialize();
} catch (err) {
if (err instanceof KameleoonError) {
switch (err.type) {
case KameleoonException.StorageWrite:
// -- Handle error case
case KameleoonException.ClientConfiguration:
// -- Handle error case
default:
break;
}
}
}
}
init();
import { KameleoonClient, KameleoonException } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
try {
await client.initialize();
} catch (err) {
switch (err.type) {
case KameleoonException.StorageWrite:
// -- Handle error case
case KameleoonException.ClientConfiguration:
// -- Handle error case
default:
break;
}
}
}
init();
Argumentos
| Nombre | Tipo | Descripción | Valor por defecto |
|---|
| useCache (opcional) | boolean | parameter for activating SDK offline mode. If true, failed polls will not return error and will use cached data if such data is available. | false |
Return value
| Tipo | Descripción |
|---|
Promise<boolean> | A promise that resolves to a boolean indicating whether the SDK was successfully initialized. Usually, if an unresolvable issue occurs, the initialize method will throw an error instead of resolving the promise. Por lo tanto, the boolean value is almost always true and typically does not provide much additional information. |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.StorageWrite | Couldn’t update storage data |
KameleoonException.ClientConfiguration | Couldn’t retrieve client configuration from Kameleoon API |
KameleoonException.MaximumRetriesReached | Maximum retries reached, request failed |
An asynchronous method for KameleoonClient initialization by fetching Kameleoon SDK related data from server or by retrieving data from local source if data is up-to-date or update interval has not been reached.
-
If the SDK configuration could not be retrieved but there is an older configuration available in SDK storage, the SDK uses the older configuration as a fallback and the
initialize does not throw an error.
-
SDK supports an offline mode.
In offline mode if solicitudes de seguimiento from any of lo siguiente methods fail due to internet connectivity issues, the SDK automatically resends the request as soon as it detects that the internet connection has been re-established:import {
KameleoonClient,
KameleoonError,
KameleoonException,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
try {
await client.initialize();
} catch (err) {
if (err instanceof KameleoonError) {
switch (err.type) {
case KameleoonException.StorageWrite:
// -- Handle error case
case KameleoonException.ClientConfiguration:
// -- Handle error case
default:
break;
}
}
}
}
init();
import { KameleoonClient, KameleoonException } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
try {
await client.initialize();
} catch (err) {
switch (err.type) {
case KameleoonException.StorageWrite:
// -- Handle error case
case KameleoonException.ClientConfiguration:
// -- Handle error case
default:
break;
}
}
}
init();
Return value
| Tipo | Descripción |
|---|
Promise<boolean> | A promise that resolves to a boolean indicating whether the SDK was successfully initialized. Usually, if an unresolvable issue occurs, the initialize method will throw an error instead of resolving the promise. Por lo tanto, the boolean value is almost always true and typically does not provide much additional information. |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.StorageWrite | Couldn’t update storage data |
KameleoonException.ClientConfiguration | Couldn’t retrieve client configuration from Kameleoon API |
KameleoonException.MaximumRetriesReached | Maximum retries reached, request failed |
Feature flags y variaciones
getVariation()
- 📨 Sends Tracking Data to Kameleoon (depending on the
track parameter)
Retrieves the Variation assigned to a given visitor for a specific feature flag.
This method takes featureKey as a mandatory argument and track as an optional argument. The track argument is optional and defaults to true.
It returns the assigned Variation for the visitor. If the visitor is not associated with any feature flag rules, the method returns the default Variation for the given feature flag.
Ensure that proper error handling is implemented in your code to manage potential exceptions.
The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It’s represented as the variation in the “Then, for everyone else…” section in a management interface.
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get variation with tracking
const variation = client.getVariation({
visitorCode,
featureKey: 'my_feature_key',
});
// -- Get variation without tracking
const variation = client.getVariation({
visitorCode,
featureKey: 'my_feature_key',
track: false,
});
// -- An Example variation:
// {
// key: 'variation_key',
// id: 123,
// experimentId: 456,
// variables: Map {
// 'variable_key' => {
// key: 'variable_key',
// type: VariableType.BOOLEAN,
// value: true,
// }
// },
// }
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get variation with tracking
const variation = client.getVariation({
visitorCode,
featureKey: 'my_feature_key',
});
// -- Get variation without tracking
const variation = client.getVariation({
visitorCode,
featureKey: 'my_feature_key',
track: false,
});
// -- An Example variation:
// {
// key: 'variation_key',
// id: 123,
// experimentId: 456,
// variables: Map {
// 'variable_key' => {
// key: 'variable_key',
// type: VariableType.BOOLEAN,
// value: true,
// }
// },
// }
}
init();
Argumentos
An object of type GetVariationParamsType with lo siguiente properties:
| Nombre | Tipo | Descripción | Por defecto |
|---|
| visitorCode (obligatorio) | string | Unique identifier of the visitor. | |
| featureKey (obligatorio) | string | Key of the feature you want to expose to a visitor. | |
| track (opcional) | boolean | An optional parameter to enable or disable tracking of the feature evaluation. | true |
Return value
| Tipo | Descripción |
|---|
Variation | An assigned Variation to a given visitor for a specific feature flag. |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed it’s initialize call. |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty. |
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length (255 characters). |
KameleoonException.FeatureFlagConfigurationNotFound | Exception indicating that the requested feature key wasn’t found in the internal configuration of the SDK. This usually means that the feature flag is not activated in the Kameleoon app (but code implementing the feature is already deployed in the application). |
KameleoonException.FeatureFlagEnvironmentDisabled | Exception indicating that feature flag is disabled for the visitor’s current environment (for example, production, staging, or development). |
getVariations()
- 📨 Sends Tracking Data to Kameleoon (depending on the
track parameter)
- 🎯 Events:
EventType.Evaluation
Retrieves a map of Variation objects assigned to a given visitor across all feature flags.
This method iterates over all available feature flags and returns the assigned Variation for each flag associated with the specified visitor. It takes visitorCode as a mandatory argument, while onlyActive and track are optional.
- If
onlyActive is set to true, the method getVariations() will return feature flags variations provided the user is not bucketed with the off variation.
- The
track parameter controls whether or not the method will track the variation assignments. By default, it is set to true. If set to false, the tracking will be disabled.
The returned map consists of feature flag keys as keys and their corresponding Variation as values. If no variation is assigned for a feature flag, the method returns the default Variation for that flag.
Proper error handling should be implemented to manage potential exceptions.
The default variation refers to the variation assigned to a visitor when they do not match any predefined delivery rules for a feature flag. In other words, it is the fallback variation applied to all users who are not targeted by specific rules. It’s represented as the variation in the “Then, for everyone else…” section in a management interface.
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get all feature flag variations with tracking
const variations = client.getVariations({
visitorCode,
});
// -- Get active feature flag variations with tracking
const variations = client.getVariations({
visitorCode,
onlyActive: true,
});
// -- Get active feature flag variations without tracking
const variations = client.getVariations({
visitorCode,
onlyActive: true,
track: false,
});
// -- An Example variations:
// Map {
// 'feature_key' => {
// key: 'variation_key',
// id: 123,
// experimentId: 456,
// variables: Map {
// 'variable_key' => {
// key: 'variable_key',
// type: VariableType.BOOLEAN,
// value: true,
// }
// },
// }
// }
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get all feature flag variations with tracking
const variations = client.getVariations({
visitorCode,
});
// -- Get active feature flag variations with tracking
const variations = client.getVariations({
visitorCode,
onlyActive: true,
});
// -- Get active feature flag variations without tracking
const variations = client.getVariations({
visitorCode,
onlyActive: true,
track: false,
});
// -- An Example variations:
// Map {
// 'feature_key' => {
// key: 'variation_key',
// id: 123,
// experimentId: 456,
// variables: Map {
// 'variable_key' => {
// key: 'variable_key',
// type: VariableType.BOOLEAN,
// value: true,
// }
// },
// }
// }
}
init();
Argumentos
An object of type GetVariationParamsType with lo siguiente properties:
| Nombre | Tipo | Descripción | Por defecto |
|---|
| visitorCode (obligatorio) | string | Unique identifier of the visitor. | |
| onlyActive (opcional) | boolean | An optional parameter indicating whether to return variations for active (true) or all (false) feature flags. | false |
| track (opcional) | boolean | An optional parameter to enable or disable tracking of the feature evaluation. | true |
Return value
| Tipo | Descripción |
|---|
Map<string, Variation> | Map that contains the assigned Variation objects of the feature flags using the keys of the corresponding features. |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed it’s initialize call. |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty. |
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length (255 characters). |
isFeatureFlagActive()
- 📨 Sends Tracking Data to Kameleoon (depending on the
track parameter)
- 🎯 Events:
EventType.Evaluation
The method isFeatureFlagActive() returns a boolean value indicating whether the visitor identified by visitorCode has the specified featureKey active. This method checks for targeting, determines the variation for the visitor, and saves this information to storage. Adicionalmente, it sends a solicitud de seguimiento.
There is also an overload of this method that allows you to pass a track parameter, which you can use to disable tracking of the feature evaluation.
Only visitors with an active feature flag must be targetted.
Kameleoon uses tracking to count sessions and visitors when you call certain methods, como por ejemplo isFeatureFlagActive(), getVariation() or getVariations().Use the default true value for the track parameter when you expose visitors to a variation and need to count them. Set the track parameter to false only if you call these methods before you expose visitors.Por ejemplo, if you call getVariations() to retrieve all variations before you expose visitors, set the track parameter to false. This setting prevents Kameleoon from prematurely counting a session. You can then trigger tracking later when you explicitly expose the visitor.Kameleoon sends tracking data every second by default. You can configure this interval up to five seconds using the tracking interval configuration option. Kameleoon groups tracking events into a single session as long as the interval between events is less than 30 minutes. If more than 30 minutes elapse between tracking events, Kameleoon counts the events as separate sessions. A visit appears in your reports 30 minutes after the last recorded event in the session.
import { KameleoonClient, CustomData } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Add CustomData with index `0` containing visitor id to check the targeting
client.addData(visitorCode, new CustomData(0, 'visitor_id'));
// -- Check if the feature flag is active for visitor
const isActive = client.isFeatureFlagActive(visitorCode, 'my_feature_key');
// -- Check if the feature flag is active for visitor without tracking
const isActive = client.isFeatureFlagActive({ visitorCode, featureKey: 'my_feature_key', track: false});
}
init();
import { KameleoonClient, CustomData } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Add CustomData with index `0` containing visitor id to check the targeting
client.addData(visitorCode, new CustomData(0, 'visitor_id'));
// -- Check if the feature flag is active for visitor
const isActive = client.isFeatureFlagActive(visitorCode, 'my_feature_key');
// -- Check if the feature flag is active for visitor without tracking
const isActive = client.isFeatureFlagActive({ visitorCode, featureKey: 'my_feature_key', track: false});
}
init();
The isFeatureFlagActive() method evaluates the served variant, not the master flag state. If you exclude rules, the method uses the Then, for everyone else serve default state. If you select Off for this default state, the method always returns false even when the master feature flag is On.
Argumentos
There are two overloads available for this method:
- Two parameters overload:
This overload is deprecated and will be removed in the next major update. Please use the new overload with an object parameter.
| Nombre | Tipo | Descripción |
|---|
| visitorCode (obligatorio) | string | unique visitor identification string, can’t exceed 255 characters in length |
| featureKey (obligatorio) | string | a unique key for feature flag |
- Object parameter overload of type
IsFeatureFlagActiveParamsType:
| Nombre | Tipo | Descripción | Por defecto |
|---|
| visitorCode (obligatorio) | string | unique visitor identification string, can’t exceed 255 characters in length | - |
| featureKey (obligatorio) | string | a unique key for feature flag | - |
| track (opcional) | boolean | a boolean indicator of whether to track the feature evaluation | true |
Return value
| Tipo | Descripción |
|---|
boolean | a boolean indicating whether the feature flag with featureKey is active for the visitor with visitorCode |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed its initialize call. |
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty. |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found for provided featureKey. |
KameleoonException.DataInconsistency | Allocated variation was found, but there is no feature flag with according featureKey |
setForcedVariation()
The method allows you to programmatically assign a specific Variation to a user, bypassing the standard evaluation process. This is especially valuable for controlled experiments where the usual evaluation logic is not required or must be skipped. It can also be helpful in scenarios like debugging or custom testing.
When a forced variation is set, it overrides Kameleoon’s real-time evaluation logic. Processes like segmentation, targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and targeting conditions during an experiment, set forceTargeting=false instead.
Simulated variations always take precedence in the execution order. If a simulated variation calculation is triggered, it will be fully processed and completed first.
A forced variation is treated the same as an evaluated variation. It is tracked in analytics and stored in the user context like any standard evaluated variation, ensuring consistency in reporting.
The method may throw exceptions under certain conditions (e.g., invalid parameters, user context, or internal issues). Proper exception handling is essential to ensure that your application remains stable and resilient.
It’s important to distinguish forced variations from simulated variations:
- Forced variations: Are specific to an individual experiment.
- Simulated variations: Affect the overall feature flag result.
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Forcing the variation "on" for the "featureKey1" feature flag for the visitor
client.setForcedVariation({
visitorCode: visitorCode,
experimentId: 9516,
variationKey: 'on',
forceTargeting: false,
});
// -- Resetting the forced variation for the "featureKey1" feature flag for the visitor
client.setForcedVariation({
visitorCode: visitorCode,
experimentId: 9516,
variationKey: null,
});
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Forcing the variation "on" for the "featureKey1" feature flag for the visitor
client.setForcedVariation({
visitorCode: visitorCode,
experimentId: 9516,
variationKey: 'on',
forceTargeting: false,
});
// -- Resetting the forced variation for the "featureKey1" feature flag for the visitor
client.setForcedVariation({
visitorCode: visitorCode,
experimentId: 9516,
variationKey: null,
});
}
init();
Argumentos
An object of type SetForcedVariationParametersType with lo siguiente properties:
| Nombre | Tipo | Descripción | Por defecto | |
|---|
| visitorCode (obligatorio) | string | Unique identifier of the visitor. | | |
| experimentId (obligatorio) | number | Experiment Id that will be targeted and selected during the evaluation process. | | |
| variationKey (obligatorio) | `string | null` | Variation Key corresponding to a Variation that should be forced as the returned value for the experiment. If the value is null, the forced variation will be reset. | |
| forceTargeting (opcional) | boolean | Indicates whether targeting for the experiment should be forced and skipped (true) or applied as in the standard evaluation process (false). | true | |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.VisitorCodeEmpty | The código de visitante is empty. |
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length (255 characters). |
KameleoonException.Initialization | Indicates that the SDK is not yet fully initialized. |
KameleoonException.FeatureFlagExperimentNotFound | Exception indicating that the requested experiment id has not been found in the SDK’s internal configuration. This is usually normal and means that the rule’s corresponding experiment has not yet been activated on Kameleoon’s side. |
KameleoonException.FeatureFlagVariationNotFound | Exception indicating that the requested variation key(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. |
KameleoonException.StorageRead | Couldn’t read storage data. |
KameleoonException.StorageWrite | Couldn’t update storage data. |
In most cases, only the basic error, KameleoonException, needs to be handled, as demonstrated in the example. Sin embargo, if different types of errors require a response, handle each one separately based on specific requirements. Adicionalmente, for enhanced reliability, general language errors can be handled by including Error.
evaluateAudiences()
- 📨 Sends Tracking Data to Kameleoon
This method evaluates visitors against all available Audiences Explorer segments and tracks those who match.
evaluateAudiences() should be called after all relevant datos del visitante has been set or updated, and just before getting a feature variation or checking a feature flag. This approach ensures that the visitor is evaluated against the most current data available, allowing for accurate audience assignment based on all criteria.
After calling this method, you can perform a detailed analysis of segment performance in Audiences Explorer.
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
client.evaluateAudiences(visitorCode);
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
client.evaluateAudiences(visitorCode);
}
init();
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode (obligatorio) | string | Unique identifier of the visitor. |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed it’s initialize call. |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty. |
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length (255 characters). |
In most cases, only the basic error, KameleoonException, needs to be handled, as demonstrated in the example. Sin embargo, if different types of errors require a response, handle each one separately based on specific requirements. Adicionalmente, for enhanced reliability, general language errors can be handled by including Error.
getDataFile()
To evaluate all feature flags, use getVariations(). This method is more efficient than calling DataFile and iterating through flags with getVariation().
Returns the current SDK configuration as a DataFile object.
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
const dataFile = client.getDataFile();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
const dataFile = client.getDataFile();
Return value
| Tipo | Descripción |
|---|
DataFile | The DataFile containing the SDK configuration |
Datos del visitante
getVisitorCode()
The getVisitorCode() method obtains a código de visitante from the browser cookie. If the código de visitante doesn’t exist, the method generates a random código de visitante (or uses the defaultVisitorCode value if you provided one) and sets the new código de visitante in a cookie.
The getVisitorCode() method allows you to set simulated variations for a visitor. When cookies (from a request or document) contain the key kameleoonSimulationFFData, the standard evaluation process is bypassed. Instead, the method directly returns a Variation based on the provided data.You can apply simulations in two ways:
- Automatically (recommended): If using Kameleoon Web Experimentation or the SDK in Hybrid mode, the cookie is created automatically when simulating a variant’s display using the Simulation Panel.
- Manually: Set the
kameleoonSimulationFFData cookie manually.
It’s important to distinguish simulated variations from forced variations:
- Simulated variations: Affect the overall feature flag result.
- Forced variations: Are specific to an individual experiment.
⚙️ Manual setupPlease ensure the kameleoonSimulationFFData cookie follows this format:
kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simulates the variation with varId of experiment expId for the given featureKey.
kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simulates the default variation (defined in the Then, for everyone else in Production, serve section) for the given featureKey.
⚠️ To ensure proper functionality, the cookie value must be encoded as a URI component using a method como por ejemplo encodeURIComponent.
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get visitor code with default value
const visitorCode = client.getVisitorCode('my_default_visitor_code');
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get visitor code with default value
const visitorCode = client.getVisitorCode('my_default_visitor_code');
}
init();
Argumentos
| Nombre | Tipo | Descripción |
|---|
defaultVisitorCode (opcional) | string | código de visitante used if there is no código de visitante in cookies |
If you don’t provide a defaultVisitorCode and there is no código de visitante stored in a cookie, the código de visitante will be randomly generated.
Return value
| Tipo | Descripción |
|---|
string | result código de visitante |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.VisitorCodeMaxLength | The código de visitante length was exceeded |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty |
addData()
The addData() method adds targeting data to storage so other methods can use the data to decide whether to target the current visitor.
The addData() method does not return any value and does not interact with Kameleoon back-end servers on its own. Instead, all the declared data is saved for future transmission using the flush method. This approach reduces the number of server calls made, as the data is typically grouped into a single server call. Tenga en cuenta que the trackConversion method also sends out any previously associated data, just like the flush method. The same is true for the getFeatureFlagVariationKey and getFeatureFlagVariable methods, if an experimentation rule is triggered.
Each visitor can only have one instance of associated data for most data types. Sin embargo, CustomData is an exception. Visitors can have one instance of associated CustomData per customDataIndex.
-
userAgent data will not be stored in storage like other data, and it will be sent with every solicitud de seguimiento for bot filtration.
-
For the data types you can use for targeting, see the supported targeting conditions.
import {
KameleoonClient,
BrowserType,
CustomData,
Browser,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Create Kameleoon Data Types
const browserData = new Browser(BrowserType.Chrome);
const customData = new CustomData(0, 'my_data');
// -- Add a single data item (tracked by default)
client.addData('my_visitor_code', browserData);
// -- Add multiple data items (tracked by default)
client.addData('my_visitor_code', browserData, customData);
// -- Add multiple data items from array (tracked by default)
const dataArr = [browserData, customData];
client.addData('my_visitor_code', ...dataArr);
// -- Add multiple data items stored locally for targeting only (not sent to the Kameleoon Data API)
client.addData({visitorCode: 'my_visitor_code', track: false, data: dataArr});
}
init();
import {
KameleoonClient,
CustomData,
Browser,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Create Kameleoon Data Types
const browserData = new Browser(BrowserType.Chrome);
const customData = new CustomData(0, 'my_data');
// -- Add a single data item (tracked by default)
client.addData('my_visitor_code', browserData);
// -- Add multiple data items (tracked by default)
client.addData('my_visitor_code', browserData, customData);
// -- Add multiple data items from array (tracked by default)
const dataArr = [browserData, customData];
client.addData('my_visitor_code', ...dataArr);
// -- Add multiple data items stored locally for targeting only (not sent to the Kameleoon Data API)
client.addData({visitorCode: 'my_visitor_code', track: false, data: dataArr});
}
init();
Argumentos
| Nombre | Tipo | Descripción | Valor por defecto |
|---|
| visitorCode (obligatorio) | string | unique visitor identification string, can’t exceed 255 characters. | |
| track (opcional) | boolean | Specifies whether the added data is eligible for tracking. When set to false, the data is stored locally and used only for targeting evaluation; it is not sent to the Kameleoon Data API. | true |
| kameleoonData (opcional) | KameleoonDataType[] | number of instances of any type of KameleoonData, can be added solely in array or as sequential arguments | |
-
kameleoonData is a variadic argument. It can be passed as one or several arguments (see the example).
-
The index or ID of the datos personalizados can be found in your Kameleoon account. Tenga en cuenta que this index starts at
0, which means that the first datos personalizados you create for a given site will be assigned 0 as its ID, not 1.
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length of 255 characters. |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty. |
KameleoonException.StorageWrite | Couldn’t update storage data. |
KameleoonException.Initialization | Method was executed before the kameleoonClient completed its initialize call. |
Check the Data Types reference for more details on how to manage different data types.
flush()
SDK Version 3
SDK Version 4
The flush() method collects the Kameleoon data linked to the visitor. It then sends a solicitud de seguimiento, along with all data added using the addData method, which has not yet been sent using one of these methods.If you don’t specify a visitorCode, the SDK flushes all of its stored data to the remote Kameleoon servers. If any previously failed solicitudes de seguimiento were stored locally in offline mode, the SDK attempts to send the stored requests before executing the latest request.The isUniqueIdentifier can be helpful in unique situations; for example, if you cannot access the anonymous visitorCode given to a visitor, but you can use an internal ID linked to that visitor through session merging.
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
const customData = new CustomData(0, 'my_data');
client.addData(visitorCode, customData);
// -- Flush added custom data for visitor
client.flush(visitorCode);
// -- Flush data for all the visitors
client.flush();
// -- Flush data with unique visitor identifier flag
const internalUserId = 'my_user_id';
client.flush(internalUserId, true);
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
const customData = new CustomData(0, 'my_data');
client.addData(visitorCode, customData);
// -- Flush added custom data for visitor
client.flush(visitorCode);
// -- Flush data for all the visitors
client.flush();
// -- Flush data with unique visitor identifier flag
const internalUserId = 'my_user_id';
client.flush(internalUserId, true);
}
init();
Argumentos
| Nombre | Tipo | Descripción | Por defecto |
|---|
| visitorCode (opcional) | string | unique visitor identification string, can’t exceed 255 characters, if not passed, all data will be flushed (sent to the remote Kameleoon servers). | - |
| isUniqueIdentifier (opcional) | boolean | an optional parameter for specifying if the visitorCode is a unique identifier. | false |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty. |
KameleoonException.Initialization | Method was executed before the kameleoonClient completed its initialize call. |
flush() takes the Kameleoon data associated with a visitor and schedules the data to be sent in the next solicitud de seguimiento. The time of the next solicitud de seguimiento is defined by the SDK Configuration trackingInterval parameter. Visitor data can be added using the addData and getRemoteVisitorData methods.If you don’t specify a visitorCode, the SDK flushes all of its stored data to the remote Kameleoon servers. If any previously failed solicitudes de seguimiento were stored locally in offline mode, the SDK attempts to send the stored requests before executing the latest request.If you need to send solicitudes de seguimiento immediately, use flushInstant() — the asynchronous version of flush that returns Promise<void>. You can await it when you need delivery guarantees (for example, before page navigation/unload), or call it without await as a fire-and-forget request:
await client.flushInstant(visitorCode) sends solicitudes de seguimiento immediately for a specific visitor and waits for completion
await client.flushInstant() sends solicitudes de seguimiento immediately for all visitors and waits for completion
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
const customData = new CustomData(0, 'my_data');
client.addData(visitorCode, customData);
// -- Flush added custom data for visitor
client.flush(visitorCode);
// -- Instantly flush added custom data for visitor (fire-and-forget)
client.flushInstant(visitorCode);
// -- Instantly flush added custom data for visitor and wait for completion
await client.flushInstant(visitorCode);
// -- Flush data for all the visitors
client.flush();
// -- Instantly flush data for all the visitors (fire-and-forget)
client.flushInstant();
// -- Instantly flush data for all the visitors and wait for complention
await client.flushInstant();
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
const customData = new CustomData(0, 'my_data');
client.addData(visitorCode, customData);
// -- Flush added custom data for visitor
client.flush(visitorCode);
// -- Instantly flush added custom data for visitor
client.flush({ visitorCode, instant: true });
// -- Flush data for all the visitors
client.flush();
// -- Instantly flush data for all the visitors
client.flush({ instant: true });
}
init();
Argumentos
| Nombre | Tipo | Descripción | Por defecto |
|---|
| visitorCode (opcional) | string | unique visitor identification string, can’t exceed 255 characters, if not passed, all data will be flushed (sent to the remote Kameleoon servers). | - |
Or an object with the type FlushParamsType, containing:| Nombre | Tipo | Descripción | Por defecto |
|---|
| visitorCode (opcional) | string | unique visitor identification string, can’t exceed 255 characters, if not passed, all data will be flushed (sent to the remote Kameleoon servers). | - |
| instant (opcional) | boolean | Boolean flag indicating whether the data should be sent instantly (true) or according to the scheduled tracking interval (false). | - |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty. |
KameleoonException.Initialization | Method was executed before the kameleoonClient completed it’s initialize call. |
getRemoteData()
The getRemoteData() method returns data that is stored for a specified site code in a remote Kameleoon server.
You can use this method to retrieve user preferences, historical data, or any other data relevant to your application’s logic. By storing this data on our highly scalable servers using our Data API, you can efficiently manage massive amounts of data and retrieve it for each of your visitors or users.
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Get remote data
const jsonData = await getRemoteData('my_data_key');
const data = JSON.parse(jsonData);
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Get remote data
const jsonData = await getRemoteData('my_data_key');
const data = JSON.parse(jsonData);
}
init();
Argumentos
| Nombre | Tipo | Descripción |
|---|
| key (obligatorio) | string | unique key with which data is associated. |
Return value
| Tipo | Descripción |
|---|
JSONType | promise with data retrieved for a specific key |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.RemoteData | Couldn’t retrieve data from the Kameleoon server. |
getRemoteVisitorData()
SDK Version 3
SDK Version 4
getRemoteVisitorData() is an asynchronous method used to retrieve Kameleoon Visits Data for the visitorCode from the Kameleoon Data API. This method stores data for making targeting decisions.Data obtained using this method is important when you want to:
- use data collected from other devices.
- access a user’s history, como por ejemplo previously visited pages during past visits.
- use data that is only accessible on the client-side, like datalayer variables and goals that only convert on the front-end.
Read this article for a better understanding of possible use cases.The isUniqueIdentifier can be helpful in unique situations; for example, if you cannot access the anonymous visitorCode given to a visitor, but you can use an internal ID linked to that visitor through session merging.
import {
KameleoonClient,
KameleoonDataType,
VisitorDataFiltersType,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Get remote visitor data and add it to storage
const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
});
// -- Get remote visitor data without adding it to storage
const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
});
// -- Get remote visitor data without adding it to storage,
// and customizing filters for retrieving visits data
const filters: VisitorDataFiltersType = {
currentVisit: true,
previousVisitAmount: 10,
customData: true,
geolocation: true,
conversions: true,
};
const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
filters,
});
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Get remote visitor data and add it to storage
const kameleoonDataList = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
});
// -- Get remote visitor data without adding it to storage
const kameleoonDataList = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
});
// -- Get remote visitor data without adding it to storage,
// and customizing filters for retrieving visits data
const filters = {
currentVisit: true,
previousVisitAmount: 10,
customData: true,
geolocation: true,
conversions: true,
};
const kameleoonDataList = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
filters,
});
}
init();
Argumentos
An object with the type RemoteVisitorDataParamsType containing:| Nombre | Tipo | Descripción | Valor por defecto |
|---|
| visitorCode (obligatorio) | string | unique visitor identification string, can’t exceed 255 characters. | - |
| shouldAddData (opcional) | boolean | boolean flag identifying whether the retrieved datos personalizados should be added to storage automatically (without calling the addData method afterwards). | true |
| filters (opcional) | VisitorDataFiltersType | filters for specifying what data should be retrieved from visits, by default, only customData is retrieved from the current and latest previous visit. | { previousVisitAmount: 1, currentVisit: true customData: true }, other filters parameters are set to false |
| isUniqueIdentifier (opcional) | boolean | optional parameter that, when true, specifies that the visitorCode is a unique identifier. | false |
Return value
| Tipo | Descripción |
|---|
KameleoonDataType[] | promise with list of Kameleoon Data retrieved |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty |
KameleoonException.RemoteData | Couldn’t retrieve data from Kameleoon server |
KameleoonException.VisitAmount | Visit amount must be a number between 1 and 25 |
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
Using parameters in getRemoteVisitorData()
The getRemoteVisitorData() method offers flexibility by allowing you to define various parameters when retrieving data on visitors. Whether you’re targeting based on goals, experiments, or variations, the same approach applies across all data types.Por ejemplo, if you want to retrieve data on visitors who completed a goal “Order transaction”, you can specify parameters within the getRemoteVisitorData() method to refine your targeting. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the previousVisitAmount parameter to 5 and conversions to true.The flexibility shown in this example is not limited to goal data. You can use parameters within the getRemoteVisitorData() method to retrieve data on a variety of visitor behaviors.Here is the list of available VisitorDataFiltersType filters:| Nombre | Tipo | Descripción | Por defecto |
|---|
| previousVisitAmount (opcional) | number | Number of previous visits to retrieve data from. Number between 1 and 25 | 1 |
| currentVisit (opcional) | boolean | If true, current visit data will be retrieved | true |
| customData (opcional) | boolean | If true, datos personalizados will be retrieved. | true |
| pageViews (opcional) | boolean | If true, page data will be retrieved. | false |
| geolocation (opcional) | boolean | If true, geolocation data will be retrieved. | false |
| device (opcional) | boolean | If true, device data will be retrieved. | false |
| browser (opcional) | boolean | If true, browser data will be retrieved. | false |
| operatingSystem (opcional) | boolean | If true, operating system data will be retrieved. | false |
| conversions (opcional) | boolean | If true, conversion data will be retrieved. | false |
| experiments (opcional) | boolean | If true, experiment data will be retrieved. | false |
| kcs (opcional) | boolean | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-on | false |
getRemoteVisitorData() is an asynchronous method for retrieving Kameleoon Visits Data for the visitorCode from the Kameleoon Data API. The method adds data to storage for other methods to use when making targeting decisions.Data obtained using this is important when you want to:
- use data collected from other devices.
- access a user’s history, como por ejemplo previously visited pages during past visits.
- use data that is only accessible on the client-side, like datalayer variables and goals that only convert on the front-end.
Read this article for a better understanding of possible use cases.import {
KameleoonClient,
KameleoonDataType,
VisitorDataFiltersType,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Get remote visitor data and add it to storage
const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
});
// -- Get remote visitor data without adding it to storage
const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
});
// -- Get remote visitor data without adding it to storage,
// and customizing filters for retrieving visits data
const filters: VisitorDataFiltersType = {
currentVisit: true,
previousVisitAmount: 10,
customData: true,
geolocation: true,
conversions: true,
};
const kameleoonDataList: KameleoonDataType[] = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
filters,
});
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Get remote visitor data and add it to storage
const kameleoonDataList = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
});
// -- Get remote visitor data without adding it to storage
const kameleoonDataList = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
});
// -- Get remote visitor data without adding it to storage,
// and customizing filters for retrieving visits data
const filters = {
currentVisit: true,
previousVisitAmount: 10,
customData: true,
geolocation: true,
conversions: true,
};
const kameleoonDataList = await getRemoteVisitorData({
visitorCode: 'my_visitor_code',
shouldAddData: false,
filters,
});
}
init();
Argumentos
An object with the type RemoteVisitorDataParamsType containing:| Nombre | Tipo | Descripción | Valor por defecto |
|---|
| visitorCode (obligatorio) | string | unique visitor identification string, can’t exceed 255 characters length | - |
| shouldAddData (opcional) | boolean | boolean flag identifying whether the retrieved datos personalizados should be added to storage automatically (without calling the addData method afterwards) | true |
| filters (opcional) | VisitorDataFiltersType | filters for specifying what data should be retrieved from visits, by default only customData is retrieved from the current and latest previous visit | { previousVisitAmount: 1, currentVisit: true customData: true }, other filters parameters are set to false |
Return value
| Tipo | Descripción |
|---|
KameleoonDataType[] | promise with list of Kameleoon Data retrieved |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty |
KameleoonException.RemoteData | Couldn’t retrieve data from Kameleoon server |
KameleoonException.VisitAmount | Visit amount must be a number between 1 and 25 |
KameleoonException.Initialization | Method was executed before initialize was done for kameleoonClient |
Using parameters in getRemoteVisitorData()
The getRemoteVisitorData() method offers flexibility, allowing you to define various parameters when retrieving data on visitors. Whether you’re targeting based on goals, experiments, or variations, the same approach applies across all data types.Por ejemplo, if you want to retrieve data on visitors who completed a goal “Order transaction”, you can specify parameters within the getRemoteVisitorData() method to refine your targeting. For instance, if you want to target only users who converted on the goal in their last five visits, you can set the previousVisitAmount parameter to 5 and conversions to true.The flexibility shown in this example is not limited to goal data. You can use parameters within the getRemoteVisitorData() method to retrieve data on a variety of visitor behaviors.Here is the list of available VisitorDataFiltersType filters:| Nombre | Tipo | Descripción | Por defecto |
|---|
| previousVisitAmount (opcional) | number | Number of previous visits to retrieve data from. Number between 1 and 25 | 1 |
| currentVisit (opcional) | boolean | If true, current visit data will be retrieved | true |
| customData (opcional) | boolean | If true, datos personalizados will be retrieved. | true |
| pageViews (opcional) | boolean | If true, page data will be retrieved. | false |
| geolocation (opcional) | boolean | If true, geolocation data will be retrieved. | false |
| device (opcional) | boolean | If true, device data will be retrieved. | false |
| browser (opcional) | boolean | If true, browser data will be retrieved. | false |
| operatingSystem (opcional) | boolean | If true, operating system data will be retrieved. | false |
| conversions (opcional) | boolean | If true, conversion data will be retrieved. | false |
| experiments (opcional) | boolean | If true, experiment data will be retrieved. | false |
| kcs (opcional) | boolean | If true, Kameleoon Conversion Score (KCS) will be retrieved. Requires the AI Predictive Targeting add-on | false |
| visitorCode (opcional) | boolean | If true, Kameleoon will retrieve the visitorCode from the most recent visit and use it for the current visit. This is necessary if you want to ensure that the visitor, identified by their visitorCode, always receives the same variation across visits for Cross-device experimentation. | true |
| personalization (opcional) | boolean | If true, personalization data will be retrieved. This is required for the personalization condition | false |
| cbs (opcional) | boolean | If true, Contextual Bandit score data will be retrieved. | false |
getVisitorWarehouseAudience()
getVisitorWarehouseAudience is an asynchronous method that retrieves all audience data associated with the visitor in your data warehouse using the specified visitorCode and warehouseKey. The warehouseKey is typically your internal user ID. The customDataIndex parameter corresponds to the Kameleoon datos personalizados that Kameleoon uses to target your visitors. Refer to the warehouse targeting documentation for additional details.
import {
KameleoonClient,
KameleoonDataType,
CustomData,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor warehouse audience data using `warehouseKey`
// and add it to storage
const customData: CustomData = await getVisitorWarehouseAudience({
visitorCode: 'my_visitor',
customDataIndex: 10,
warehouseKey: 'my_key',
});
// -- Get visitor warehouse audience data using `visitorCode`
// and add it to storage
const customData: CustomData = await getVisitorWarehouseAudience({
visitorCode: 'my_visitor',
customDataIndex: 10,
});
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Get visitor warehouse audience data using `warehouseKey`
// and add it to storage
const customData = await getVisitorWarehouseAudience({
visitorCode: 'my_visitor',
customDataIndex: 10,
warehouseKey: 'my_key',
});
// -- Get visitor warehouse audience data using `visitorCode`
// and add it to storage
const customData = await getVisitorWarehouseAudience({
visitorCode: 'my_visitor',
customDataIndex: 10,
});
}
init();
Argumentos
Parameters object consisting of:
| Nombre | Tipo | Descripción |
|---|
| visitorCode (obligatorio) | string | unique visitor identification string, can’t exceed 255 characters length |
| customDataIndex (obligatorio) | number | number representing the index of the datos personalizados you want to use to target your Warehouse Audiences |
| warehouseKey (opcional) | string | unique key to identify the warehouse data (usually, your internal user ID) |
Return value
| Tipo | Descripción |
|---|
Promise<CustomData | null> | promise containing CustomData with the associated warehouse data or null if there was no data |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty |
KameleoonException.RemoteData | Couldn’t retrieve data from Kameleoon server |
setLegalConsent()
Consent information is synchronized between the Kameleoon Engine (application file engine.js) and the JS SDK. This synchronization means that once consent is set on either the Engine or the SDK, it’s automatically set for both. This feature eliminates the need for manual consent handling and ensures that SDKs operate in compliance with user preferences.If you use Kameleoon in Hybrid mode, we recommend reading the consent section in our Hybrid experimentation article
When handling legal consent, it’s important to use the getVisitorCode method from KameleoonClient, not the deprecated method from KameleoonUtils. Adicionalmente, this method does not accept domain as an argument. Instead, pass it to the KameleoonClient constructor. Refer to the above example.
The setLegalConsent method specifies whether the visitor has given legal consent to use personal data. Setting the legalConsent parameter to false limits the types of data that you can include in solicitudes de seguimiento. This method helps you adhere to legal and regulatory requirements while responsibly managing datos del visitante. You can find more information on personal data in the consent management policy.
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init(): Promise<void> {
await client.initialize();
const visitorCode = client.getVisitorCode();
client.setLegalConsent(visitorCode, true);
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init() {
await client.initialize();
const visitorCode = client.getVisitorCode();
client.setLegalConsent(visitorCode, true);
}
init();
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode (obligatorio) | string | unique visitor identification string, can’t exceed 255 characters. length |
| consent (obligatorio) | boolean | a boolean value representing the legal consent status. true indicates that the visitor has given legal consent. false indicates that the visitor has never provided or has withdrawn legal consent. |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.VisitorCodeMaxLength | The código de visitante length exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty |
Consent revocation behavior
When you call setLegalConsent() with consent=false, the SDK does not delete the kameleoonVisitorCode cookie. Instead, it stops extending the cookie’s expiration date, allowing the cookie to persist until it naturally expires.
If your compliance requirements demand the immediate removal of the cookie file upon opt-out, you must delete it manually using your framework’s native cookie management methods. The SDK will not remove the file automatically.
Objetivos y analítica de terceros
trackConversion()
SDK Version 3
SDK Version 4
- _📨 Sends Tracking Data to Kameleoon
Use this method to track a conversion for a specific goal and user. This method requires visitorCode and goalId. In addition, this method also accepts an optional revenue argument. 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.If you specify a visitorCode and set isUniqueIdentifier to true, the trackConversion() method uses it as the unique visitor identifier, which is useful for cross-device experimentation because the SDK links the flushed data with the visitor that is associated with the specified identifier.The isUniqueIdentifier can also be useful in other edge-case scenarios, como por ejemplo when you can’t access the anonymous visitorCode that was originally assigned to the visitor, but you do have access to an internal ID that is connected to the anonymous visitor using session merging capabilities.
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init(): Promise<void> {
const experimentId = 123;
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Track conversion
client.trackConversion({ visitorCode, revenue: 20000, goalId: 123 });
// -- Track conversion with unique visitor identifier flag
const internalUserId = 'my_user_id';
client.trackConversion({
visitorCode: internalUserId,
revenue: 20000,
goalId: 123,
isUniqueIdentifier: true,
});
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init() {
const experimentId = 123;
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Track conversion
client.trackConversion({ visitorCode, revenue: 20000, goalId: 123 });
// -- Track conversion with unique visitor identifier flag
const internalUserId = 'my_user_id';
client.trackConversion({
visitorCode: internalUserId,
revenue: 20000,
goalId: 123,
isUniqueIdentifier: true,
});
}
init();
Argumentos
Parameters object consisting of:| Nombre | Tipo | Descripción | Por defecto |
|---|
| visitorCode (obligatorio) | string | Unique identifier of the visitor. | |
| goalId (obligatorio) | number | ID of the goal. | |
| revenue (opcional) | number | Revenue of the conversion. | 0 |
| isUniqueIdentifier (opcional) | boolean | An optional parameter for specifying if the visitorCode is a unique identifier. | false |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty. |
KameleoonException.StorageWrite | Couldn’t update storage data. |
- 📨 Sends Tracking Data to Kameleoon
Use this method to track a conversion for a specific goal and user. This method requires visitorCode and goalId. In addition, this method also accepts an optional revenue, negative and metadata arguments. 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.import { KameleoonClient, CustomData } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init(): Promise<void> {
const experimentId = 123;
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Track conversion
client.trackConversion({
visitorCode,
revenue: 20000,
goalId: 123,
metadata: [new CustomData(0, 'value')],
negative: true,
});
}
init();
import { KameleoonClient, CustomData } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init() {
const experimentId = 123;
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Track conversion
client.trackConversion({
visitorCode,
revenue: 20000,
goalId: 123,
metadata: [new CustomData(0, 'value')],
negative: true,
});
}
init();
Argumentos
Parameters object consisting of:| Nombre | Tipo | Descripción | Por defecto |
|---|
| visitorCode (obligatorio) | string | Unique identifier of the visitor. | |
| goalId (obligatorio) | number | ID of the goal. | |
| negative (opcional) | boolean | Defines if the revenue is positive or negative. | false |
| revenue (opcional) | number | Revenue of the conversion. | 0 |
| metadata (opcional) | CustomData[] | Metadata of the conversion. Must be defined beforehand in the Kameleoon App. | undefined |
metadata values are accessible through raw data exports and the results page.If the metadata parameter is provided, Kameleoon will use these specified values for the current conversion instead of what was previously collected using the addData() method. If the parameter is omitted, Kameleoon will use the last tracked values for those CustomData prior to the conversion and within the same visit.Kameleoon will only consider the metadata values that are explicitly passed as parameters to the trackConversion() method.In the example below, Kameleoon will associate the conversion only with the datos personalizados value explicitly provided as a parameter (here: index 5 with the value ‘Amex Credit Card’).kameleoonClient.addData(visitorCode, new CustomData(5, 'Credit Card'), new CustomData(9, 'Express Delivery'));
kameleoonClient.trackConversion({
visitorCode,
goalId: 1000,
metadata: [new CustomData(5, 'Amex Credit Card')]
});
kameleoonClient.addData(visitorCode, new CustomData(5, 'Credit Card'), new CustomData(9, 'Express Delivery'));
kameleoonClient.trackConversion({
visitorCode,
goalId: 1000,
metadata: [new CustomData(5, 'Amex Credit Card')]
});
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty. |
KameleoonException.StorageWrite | Couldn’t update storage data. |
getEngineTrackingCode()
Kameleoon integrates with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To track server-side experiments correctly, call the getEngineTrackingCode() method after the visitor triggers an experiment. The SDK returns JavaScript queue commands for the experiments that the visitor triggered during the previous five seconds. When you insert this code into the page, Engine.js processes the commands and sends the exposure events through the active analytics integration.
Refer to hybrid experimentation for more information on implementing this method.
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Trigger feature experiment
// -- E.g., result `variationKey` id is `200`, and implicit experiment id is `100`.
client.getVariation({ visitorCode: 'visitor_code', featureKey: 'my_feature_key' });
// -- Get tracking code
const engineCode = client.getEngineTrackingCode('visitor_code');
// -- Result engine code will look like this
// `
// window.kameleoonQueue = window.kameleoonQueue || [];
// window.kameleoonQueue.push(['Experiments.assignVariation', 100, 200, true]);
// window.kameleoonQueue.push(['Experiments.trigger', 100, true]);
// `
// -- Insert tracking code into the page
const script = document.createElement('script');
script.textContent = engineCode;
document.body.appendChild(script);
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Trigger feature experiment
// -- E.g., result `variationKey` id is `200`, and implicit experiment id is `100`
client.getVariation({ visitorCode: 'visitor_code', featureKey: 'my_feature_key' });
// -- Get tracking code
const engineCode = client.getEngineTrackingCode('visitor_code');
// -- Result engine code will look like this
// `
// window.kameleoonQueue = window.kameleoonQueue || [];
// window.kameleoonQueue.push(['Experiments.assignVariation', 100, 200, true]);
// window.kameleoonQueue.push(['Experiments.trigger', 100, true]);
// `
// -- Insert tracking code into the page
const script = document.createElement('script');
script.textContent = engineCode;
document.body.appendChild(script);
}
init();
-
To use this feature, implement both the JavaScript SDK and Kameleoon Engine.js. Because Engine.js is used only for tracking in this flow, you can install the asynchronous tag before the closing
</body> tag.
-
You can insert the returned tracking code directly into an HTML
<script> tag.
<html lang="en">
<body>
<script>
const engineTrackingCode = `
window.kameleoonQueue = window.kameleoonQueue || [];
window.kameleoonQueue.push(['Experiments.assignVariation', 123456, 7890, true]);
window.kameleoonQueue.push(['Experiments.trigger', 123456, true]);
window.kameleoonQueue.push(['Experiments.assignVariation', 234567, 8901, true]);
window.kameleoonQueue.push(['Experiments.trigger', 234567, true]);
`;
const script = document.createElement('script');
script.textContent = engineTrackingCode;
document.body.appendChild(script);
</script>
</body>
</html>
En este ejemplo, 123456 and 234567 are experiment IDs, and 7890 and 8901 are variation IDs. In your implementation, the SDK generates these values in the returned tracking code.
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode (obligatorio) | string | Unique identifier of the visitor. |
Return value
| Tipo | Descripción |
|---|
string | JavaScript code to insert into the page. |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.VisitorCodeMaxLength | The código de visitante length exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty. |
Eventos
SDK Version 3
SDK Version 4
Envío de eventos de exposición a herramientas externas
Kameleoon offers built-in integrations with various analytics and CDP solutions, como por ejemplo Mixpanel, Google Analytics 4, Segment…. To ensure that you can track and analyze your server-side experiments, Kameleoon provides a method, getEngineTrackingCode(), that returns the JavasScript code to be inserted in your page. The code automatically sends the exposure events to your analytics solution. The SDK builds a tracking code for your active analytics solution based on the experiments that the visitor has triggered in the last five seconds.
Para más información sobre hybrid experimentation, please refer to this article.The getEngineTrackingCode() method returns the Kameleoon tracking code for the current visitor. The tracking code is based on the experiments that were triggered during the last five seconds.To benefit from this feature, you will need to implement both the JavaScript SDK and our Kameleoon JavaScript tag. We recommend you implement the Kameleoon asynchronous tag, which you can install before closing the <body> tag in your HTML page, as it will only be used for tracking purposes.
onEvent()
Method onEvent() fires a callback when a specific event is triggered. The callback function can access the data associated with the event.
The SDK methods in this documentation note which event types they trigger, if any.You can only assign one callback to each EventType.
import {
KameleoonClient,
EventType,
EvaluationEventDataType,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Define logic to be executed on SDK event
client.onEvent(EventType.Evaluation, (eventData: EvaluationEventDataType) => {
// -- My Logic
});
}
init();
import { KameleoonClient, EventType } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Define logic to be executed on SDK event
client.onEvent(EventType.Evaluation, (eventData) => {
// -- My Logic
});
}
init();
Events
Events are defined in the EventType enum. Depending on the event type, the eventData parameter will have a different type.| Tipo | eventData type | Descripción |
|---|
EventType.Evaluation | EvaluationEventDataType | Triggered when the SDK evaluates any variation for a feature flag. It is triggered regardless of the result variation. |
EventType.ConfigurationUpdate | ConfigurationUpdateEventDataType | Triggered when the SDK receives a configuration update from the server (when using real-time streaming). |
Argumentos
| Nombre | Tipo | Descripción |
|---|
| event (obligatorio) | EventType | a type of the event to associate with the callback. |
| callback (obligatorio) | (eventData: EventDataType<EventType>) => void | a callback function with the eventData parameter that is called when a configuration update occurs. |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed the initialize call. |
Sending exposure events to external tools
Kameleoon offers built-in integrations with various analytics and CDP solutions, como por ejemplo Mixpanel, Google Analytics 4, Segment…. To ensure that you can track and analyze your server-side experiments, Kameleoon provides a method, getEngineTrackingCode(), that returns the JavasScript code to be inserted in your page. The code automatically sends the exposure events to your analytics solution. The SDK builds a tracking code for your active analytics solution based on the experiments that the visitor has triggered in the last five seconds.
Para más información sobre hybrid experimentation, please refer to this article.The getEngineTrackingCode() method returns the Kameleoon tracking code for the current visitor. The tracking code is based on the experiments that were triggered during the last five seconds.To benefit from this feature, you will need to implement both the JavaScript SDK and our Kameleoon JavaScript tag. We recommend you implement the Kameleoon asynchronous tag, which you can install before closing the <body> tag in your HTML page, as it will only be used for tracking purposes.
Tipos de datos
Kameleoon Data types are helper classes used to store data in storage in predefined forms.
During the flush execution, the SDK collects all data and sends it with the solicitud de seguimiento.
Data available in the SDK is not available for targeting and reporting in the Kameleoon app until you add the data (for example, by using the addData() methodt).
See use visit history to target users for more information.
If you are using hybrid mode, call getRemoteVisitorData() to automatically fill all data that Kameleoon has previously collected.
Browser
Since JavaScript SDK 4.10.0, Browser is automatically detected based on the User-Agent string. Sin embargo, you can still manually override it if needed.
Browser contains browser information.
Each visitor can only have one Browser. Adding second a Browser overwrites the first one.
| Nombre | Tipo | Descripción |
|---|
| browser (obligatorio) | BrowserType | predefined browser type (Chrome, InternetExplorer, Firefox, Safari, Opera, Other). |
| version (opcional) | number | version of the browser, floating point number represents major and minor version of the browser. |
import {
KameleoonClient,
BrowserType,
Browser,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Add new browser data to client
const browser = new Browser(BrowserType.Chrome, 86.1);
client.addData('my_visitor_code', browser);
}
init();
import {
KameleoonClient,
BrowserType,
Browser,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Add new browser data to client
const browser = new Browser(BrowserType.Chrome, 86.1);
client.addData('my_visitor_code', browser);
}
init();
UniqueIdentifier
UniqueIdentifier data is used as marker for unique visitor identification.
If you add UniqueIdentifier for a visitor, visitorCode is used as the unique visitor identifier, which is useful for Cross-device experimentation. Associating a UniqueIdentifier with a visitor notifies the SDK that the visitor is linked to another visitor.
The isUniqueIdentifier can be helpful in unique situations; for example, if you cannot access the anonymous visitorCode given to a visitor, but you can use an internal ID linked to that visitor through session merging.
Each visitor can only have one UniqueIdentifier. Adding another UniqueIdentifier overwrites the first one.
| Nombre | Tipo | Descripción |
|---|
| value (obligatorio) | boolean | value that specifies if the visitor is associated with another visitor, false implies that the visitor is not associated with any other visitor. |
import { KameleoonClient, UniqueIdentifier } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Add unique identifier to a visitor
client.addData('my_visitor_code', new UniqueIdentifier(true));
}
init();
import { KameleoonClient, UniqueIdentifier } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Add unique identifier to a visitor
client.addData('my_visitor_code', new UniqueIdentifier(true));
}
init();
Conversion
The Conversion data set stored here can be used to filter experiment and personalization reports by any goal associated with it.
- Each visitor can have multiple
Conversion objects.
- You can find the
goalId in the Kameleoon app.
ConversionParametersType conversionParameters - an object with conversion parameters described below
| Nombre | Tipo | Descripción | Por defecto |
|---|
| goalId (obligatorio) | number | ID of the goal. | |
| revenue (opcional) | float | Revenue of the conversion | 0 |
| negative (opcional) | boolean | Defines if the revenue is positive or negative. | false |
| metadata (opcional) | CustomData[] | Metadata of the conversion. | undefined |
import {
KameleoonClient,
ConversionParametersType,
Conversion,
CustomData,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Defined conversion parameters
const conversionParameters: ConversionParametersType = {
goalId: 123,
revenue: 10000,
negative: true,
metadata: [new CustomData(0, 'value')],
};
// -- Add new conversion data to client
const conversion = new Conversion(conversionParameters);
client.addData('my_visitor_code', conversion);
}
init();
import { KameleoonClient, Conversion, CustomData } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Defined conversion parameters
const conversionParameters = {
goalId: 123,
revenue: 10000,
negative: true,
metadata: [new CustomData(0, 'value')],
};
// -- Add new conversion data to client
const conversion = new Conversion(conversionParameters);
client.addData('my_visitor_code', conversion);
}
init();
Cookie
Cookie contains information about the cookie stored on the visitor’s device.
-
Generally, the JavaScript SDK will attempt to use a
localStorage cookie for the conditions. If localStorage is not possible, the SDK can use Cookie data as an alternative.
-
Each visitor can only have one
Cookie. Adding a second Cookie overwrites the first one.
| Nombre | Tipo | Descripción |
|---|
| cookie (obligatorio) | CookieType[] | A list of CookieType objects consisting of cookie keys and values. |
import { KameleoonClient, CookieType, Cookie } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Add new cookie data to client
const cookieData: CookieType[] = [
{ key: 'key_1', value: 'value_1' },
{ key: 'key_2', value: 'value_2' },
];
const cookie = new Cookie(cookieData);
client.addData('my_visitor_code', cookie);
}
init();
import { KameleoonClient, Cookie } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Add new cookie data to client
const cookieData = [
{ key: 'key_1', value: 'value_1' },
{ key: 'key_2', value: 'value_2' },
];
const cookie = new Cookie(cookieData);
client.addData('my_visitor_code', cookie);
}
init();
Methods
Cookie data has a static utility method, fromString, that you can use to create a cookie by parsing a string that contains valid cookie data.
The method accepts string as a parameter and returns an initialized Cookie instance.
import { Cookie } from '@kameleoon/javascript-sdk';
const cookieString = 'key_1=value_1; key_2=value_2';
const cookie: Cookie = Cookie.fromString(cookieString);
// -- The result cookie will contain the following cookie array
// [
// { key: 'key_1', value: 'value_1' },
// { key: 'key_2', value: 'value_2' },
// ]
import { Cookie } from '@kameleoon/javascript-sdk';
const cookieString = 'key_1=value_1; key_2=value_2';
const cookie = Cookie.fromString(cookieString);
// -- The result cookie will contain the following cookie array
// [
// { key: 'key_1', value: 'value_1' },
// { key: 'key_2', value: 'value_2' },
// ]
GeolocationData
GeolocationData contains the visitor’s geolocation details.
Each visitor can only have one GeolocationData. Adding a second GeolocationData overwrites the first one.
An object parameter with the type GeolocationInfoType contains lo siguiente fields:
| Nombre | Tipo | Descripción |
|---|
| country (obligatorio) | string | The country of the visitor. |
| region (opcional) | string | The region of the visitor. |
| city (opcional) | string | The city of the visitor. |
| postalCode (opcional) | string | The postal code of the visitor. |
| coordinates (opcional) | [number, number] | Coordinates array tuple of two location values (latitude and longitude). Coordinate number represents decimal degrees. |
import {
KameleoonClient,
GeolocationData,
GeolocationInfoType,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Add geolocation data
const geolocationInfo: GeolocationInfoType = {
country: 'France',
region: 'Île-de-France',
city: 'Paris',
postalCode: '75008',
coordinates: [48.8738, 2.295],
};
const geolocationData = new GeolocationData(geolocationInfo);
client.addData('my_visitor_code', geolocationData);
}
init();
import { KameleoonClient, GeolocationData } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Add geolocation data
const geolocationInfo = {
country: 'France',
region: 'Île-de-France',
city: 'Paris',
postalCode: '75008',
coordinates: [48.8738, 2.295],
};
const geolocationData = new GeolocationData(geolocationInfo);
client.addData('my_visitor_code', geolocationData);
}
init();
CustomData
CustomData allows any type of data to be easily associated with each visitor. It can then be used as a targeting condition in segments or as a filter/breakdown in experiment reports.
To learn more about datos personalizados, please refer to this article.
| Nombre | Tipo | Descripción | Por defecto |
|---|
| index/name (obligatorio) | number/string | Index or Name of the datos personalizados. Either index or name must be provided to identify the data. | |
| overwrite (opcional) | boolean | Flag to explicitly control how the values are stored and how they appear in reports. See more | true |
| value (obligatorio) | string[] | The datos personalizados value. It must be stringified to match the string type. Note: value is variadic. | |
-
Each visitor is allowed only one
CustomData for each unique index. Adding another CustomData with the same index will replace the existing one.
-
The datos personalizados ‘index’ can be found in the Custom Data dashboard under the “INDEX” column.
-
To prevent the SDK from sending data with the selected index to Kameleoon servers for privacy reasons, enable the option: Use this data only locally for targeting purposes when creating datos personalizados.
-
Adding a
CustomData instance created with a name when the SDK instance is not initialized or the name is not registered, will result in the data being ignored.
import { KameleoonClient, CustomData } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
const dataItemOne = 'abc';
const dataItemTwo = JSON.stringify(100);
const dataItemThree = JSON.stringify({ a: 200, b: 300 });
const customDataIndex = 0;
// -- Create custom data using single parameter
const customData = new CustomData(customDataIndex, dataItemOne);
// -- Create custom data using overwrite flag
const customData = new CustomData(customDataIndex, false, dataItemOne);
// -- Create custom data using name instead of index
const customData = new CustomData('customDataName', dataItemOne);
// -- Create custom data using variadic number of parameters
const customData = new CustomData(customDataIndex, dataItemOne, dataItemTwo);
// -- Create custom data using an array of values
const dataList = [dataItemOne, dataItemTwo, dataItemThree];
const customData = new CustomData(customDataIndex, ...dataList);
// -- Create custom data using overwrite flag
const customData = new CustomData(customDataIndex, false, ...dataList);
// -- Create custom data using name instead of index
const customData = new CustomData('customDataName', false, ...dataList);
// -- Add custom data
client.addData('my_visitor_code', customData);
}
init();
import { KameleoonClient, CustomData } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
const dataItemOne = 'abc';
const dataItemTwo = JSON.stringify(100);
const dataItemThree = JSON.stringify({ a: 200, b: 300 });
const customDataIndex = 0;
// -- Create custom data using single parameter
const customData = new CustomData(customDataIndex, dataItemOne);
// -- Create custom data using overwrite flag
const customData = new CustomData(customDataIndex, false, dataItemOne);
// -- Create custom data using name instead of index
const customData = new CustomData('customDataName', dataItemOne);
// -- Create custom data using variadic number of parameters
const customData = new CustomData(customDataIndex, dataItemOne, dataItemTwo);
// -- Create custom data using an array of values
const dataList = [dataItemOne, dataItemTwo, dataItemThree];
const customData = new CustomData(customDataIndex, ...dataList);
// -- Create custom data using overwrite flag
const customData = new CustomData(customDataIndex, false, ...dataList);
// -- Create custom data using name instead of index
const customData = new CustomData('customDataName', false, ...dataList);
// -- Add custom data
client.addData('my_visitor_code', customData);
}
init();
Device
Since JavaScript SDK 4.10.0, Device is automatically detected based on the User-Agent string. Sin embargo, you can still manually override it if needed.
Device contains information about your device.
Each visitor can have only one Device. Adding a second Device overwrites the first one.
| Nombre | Tipo | Descripción |
|---|
| deviceType (obligatorio) | DeviceType | possible types for device type (PHONE, TABLET, DESKTOP) |
import { KameleoonClient, DeviceType, Device } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Add device data
const device = new Device(DeviceType.Desktop);
client.addData('my_visitor_code', device);
}
init();
import { KameleoonClient, DeviceType, Device } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Add device data
const device = new Device(DeviceType.Desktop);
client.addData('my_visitor_code', device);
}
init();
OperatingSystem
Since JavaScript SDK 4.10.0, OperatingSystem is automatically detected based on the User-Agent string. Sin embargo, you can still manually override it if needed.
OperatingSystem contains information about the operating system on the visitor’s device.
Each visitor can only have one OperatingSystem. Adding a second OperatingSystem overwrites the first one.
| Nombre | Tipo | Descripción |
|---|
| operatingSystem (obligatorio) | OperatingSystemType | possible types for device type: WINDOWS_PHONE, WINDOWS, ANDROID, LINUX, MAC, and IOS |
import {
KameleoonClient,
OperatingSystem,
OperatingSystemType,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Add operating system data
const operatingSystem = new OperatingSystem(OperatingSystemType.Windows);
client.addData('my_visitor_code', operatingSystem);
}
init();
import {
KameleoonClient,
OperatingSystem,
OperatingSystemType,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Add operating system data
const operatingSystem = new OperatingSystem(OperatingSystemType.Windows);
client.addData('my_visitor_code', operatingSystem);
}
init();
PageView
Since JavaScript SDK 4.10.0, PageView is automatically detected based on the window.location?.href and document.title. Sin embargo, you can still manually override it if needed.
PageView contains information about your web page.
Each visitor can have one PageView per unique URL. Adding a second PageView with the same URL notifies the SDK that the visitor re-visited the page.
PageViewParametersType pageViewParameters - an object with page view parameters described below
| Nombre | Tipo | Descripción |
|---|
| urlAddress (obligatorio) | string | url address of the page to track. |
| title (obligatorio) | string | title of the web page. |
| referrer (opcional) | number[] | an optional parameter containing a list of referrer indices, has no default value. |
You can find the index or referrer ID in your Kameleoon account. Tenga en cuenta que this index starts at 0, meaning the first acquisition channel you create for a given site will be assigned 0 as its ID, not 1.
import {
KameleoonClient,
PageViewParametersType,
PageView,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Define page view parameters
const pageViewParameters: PageViewParametersType = {
urlAddress: 'www.example.com',
title: 'my example',
referrers: [123, 456],
};
// -- Add page view data
const pageView = new PageView(pageViewParameters);
client.addData('my_visitor_code', pageView);
}
init();
import { KameleoonClient, PageView } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Define page view parameters
const pageViewParameters = {
urlAddress: 'www.example.com',
title: 'my example',
referrers: [123, 456],
};
// -- Add page view data
const pageView = new PageView(pageViewParameters);
client.addData('my_visitor_code', pageView);
}
init();
UserAgent
UserAgent lets you store information on the visitor’s user-agent. Server-side experiments are more likely to be affected by bot traffic than client-side experiments. Kameleoon uses the IAB/ABC International Spiders and Bots List to tackle this issue and recognize known bots and spiders. Kameleoon also uses the UserAgent field to filter out bots and other unwanted traffic that might distort your conversion metrics. For more details, see our help article on bot filtering.
If you use internal bots, we suggest that you pass the value curl/8.0 of the userAgent to exclude them from our analytics.
Visitor can only have one UserAgent. Adding a second UserAgent overwrites the first one.
| Nombre | Tipo | Descripción |
|---|
| value (obligatorio) | string | value used for comparison |
If you run Kameleoon in an hybrid mode, your feature experiments are automatically protected against bot traffic. This protection occurs because Kameleoon collects the user-agent automatically on the front-end. Por lo tanto, you don’t need to pass the user-agent or any other parameter to filter bots and spiders.If you use internal bots, we suggest that you pass the value curl/8.0 of the userAgent to exclude them from our analytics.
import { KameleoonClient, UserAgent } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Add user agent data
const userAgent = new UserAgent('my_unique_value');
client.addData('my_visitor_code', userAgent);
}
init();
import { KameleoonClient, UserAgent } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Add user agent data
const userAgent = new UserAgent('my_unique_value');
client.addData('my_visitor_code', userAgent);
}
init();
ApplicationVersion
ApplicationVersion represents the semantic version number of your application.
A visitor can have only one ApplicationVersion. Adding a second instance will overwrite the first one.
| Nombre | Tipo | Descripción |
|---|
| version (opcional) | string | The mobile application version. This field must follow semantic versioning. Accepted formats are major, major.minor, or major.minor.patch. |
import { KameleoonClient, ApplicationVersion } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Add application version
const applicationVersion = new ApplicationVersion('1.2');
client.addData('my_visitor_code', applicationVersion);
}
init();
import { KameleoonClient, ApplicationVersion } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Add application version
const applicationVersion = new ApplicationVersion('1.2');
client.addData('my_visitor_code', applicationVersion);
}
init();
Tipos devueltos
DataFile
The DataFile contains the SDK configuration details.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|
| featureFlags | Map<string, FeatureFlag> | A map of FeatureFlag objects, keyed by feature flag keys. |
| dateModified | number | The timestamp (in milliseconds) indicating when the DataFile was last modified. |
import { FeatureFlag } from '@kameleoon/javascript-sdk';
// Retrieves the map of feature flags from the DataFile.
// The map is keyed by feature flag identifiers, with each value being a FeatureFlag object.
const featureFlags: Map<string, FeatureFlag> = dataFile.featureFlags;
// Retrieves the last modification timestamp of the DataFile.
// The value is a number representing milliseconds since the Unix epoch.
const dateModified: number = dataFile.dateModified;
// Retrieves the map of feature flags from the DataFile.
// The map is keyed by feature flag identifiers, with each value being a FeatureFlag object.
const featureFlags = dataFile.featureFlags;
// Retrieves the last modification timestamp of the DataFile.
// The value is a number representing milliseconds since the Unix epoch.
const dateModified = dataFile.dateModified;
FeatureFlag
The FeatureFlag represents a set of properties that define a feature flag itself — for example, its Variations, Rules, environment status, and other related details.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|
| environmentEnabled | boolean | Indicating whether the feature flag is enabled in the current environment. |
| defaultVariationKey | string | The key of the default variation associated with the feature flag. |
| variations | Map<string, Variation> | A map of Variation objects, keyed by variation keys. |
| rules | Rule[] | A list of Rule objects |
import { Variation, Rule } from '@kameleoon/javascript-sdk';
// Check whether the feature flag is enabled in the current environment
const isEnvironmentEnabled: boolean = featureFlag.environmentEnabled;
// Retrieve the key of the default variation
const defaultVariationKey: string = featureFlag.defaultVariationKey;
// Retrieve all variations of the feature flag as a map (key = variation key, value = Variation object)
const variations: Map<string, Variation> = featureFlag.variations;
// Retrieve all targeting rules associated with the feature flag
const rules: Rule[] = featureFlag.rules;
// Check whether the feature flag is enabled in the current environment
const isEnvironmentEnabled = featureFlag.environmentEnabled;
// Retrieve the key of the default variation
const defaultVariationKey = featureFlag.defaultVariationKey;
// Retrieve all variations of the feature flag as a map (key = variation key, value = Variation object)
const variations = featureFlag.variations;
// Retrieve all targeting rules associated with the feature flag
const rules = featureFlag.rules;
Rule
The Rule represents a set of properties that define a rule itself — for example, its Variations.
It can be extended with additional information if required by clients. If you need more details, please contact your Customer Success Manager.
| Nombre | Tipo | Descripción |
|---|
| variations | Map<string, Variation> | A map of Variation objects, keyed by variation keys. |
import { Variation } from '@kameleoon/javascript-sdk';
// Retrieve all variations of the rule as a map (key = variation key, value = Variation object)
const variations: Map<string, Variation> = rule.variations;
// Retrieve all variations of the rule as a map (key = variation key, value = Variation object)
const variations = rule.variations;
Variation
Variation contains information about the assigned variation to the visitor (or the default variation, if no specific assignment exists).
| Nombre | Tipo | Descripción |
|---|
| name | string | name of the variation. |
| key | string | key of the variation. |
| id | number or null | id of the variation or null if the visitor landed on the default variation. |
| experimentId | number or null | id of the experiment or null if the visitor landed on the default variation. |
| variables | Map<string, Variable> | map of variables for the variation, where key is the variable key and value is the variable object. |
- Ensure that your code handles the case where
id or experimentId is null, indicating a default variation.
- The
variables map might be empty if no variables are associated with the variation.
// Retrieving the variation name
const variationName = variation.name;
// Retrieving the variation key
const variationKey = variation.key;
// Retrieving the variation id
const variationId = variation.id;
// Retrieving the experiment id
const experimentId = variation.experimentId;
// Retrieving the variables map
const variables = variation.variables;
// Retrieving the variation name
const variationName = variation.name;
// Retrieving the variation key
const variationKey = variation.key;
// Retrieving the variation id
const variationId = variation.id;
// Retrieving the experiment id
const experimentId = variation.experimentId;
// Retrieving the variables map
const variables = variation.variables;
Variable
Variable contains information about a variable associated with the assigned variation.
| Nombre | Tipo | Descripción |
|---|
| key | string | The unique key identifying the variable. |
| type | string | The type of the variable. Possible values: BOOLEAN, NUMBER, STRING, JSON, JS, CSS. |
| value | any | The value of the variable, which can be of lo siguiente types: boolean, number, String, Record<string, any>, any[]. |
// Retrieving the variables map
const variables = variation.variables;
// Variable type can be retrieved for further processing
const type = variables.get('isDiscount')?.type || '';
// Retrieving the variable value by key
const isDiscount = variables.get('isDiscount')?.value || false;
// Variable value can be of different types
const title = variables.get('title')?.value || '';
// Retrieving the variables map
const variables = variation.variables;
// Variable type can be retrieved for further processing
const type = variables.get('isDiscount')?.type || '';
// Retrieving the variable value by key
const isDiscount = variables.get('isDiscount')?.value || false;
// Variable value can be of different types
const title = variables.get('title')?.value || '';
Métodos obsoletos
These methods are deprecated and will be removed in the next major update.
getFeatureFlagVariationKey()
The getFeatureFlagVariationKey() method retrieves the variation key for a visitor identified by a visitorCode. This method includes a targeting check that identifies the appropriate variation exposed to the visitor, saves it to storage, and sends a solicitud de seguimiento.
When a user is not associated with a feature flag, the SDK randomly returns a variation key according to the feature flag rules. If the user has already been registered with the feature flag, the SDK will detect this association and return the user’s previous variation key value. Sin embargo, if the user does not meet any of the defined rules, the SDK will return the default value specified in Kameleoon’s feature flag delivery rules. It’s important to note that the default value can be a variation key, a boolean value, or another data type, depending on the feature flag’s configuration.
import { KameleoonClient, CustomData } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Add CustomData with index `0` containing visitor id to check the targeting
client.addData(new CustomData(0, 'visitor_id'));
// -- Get visitor feature flag variation key
const variationKey = client.getFeatureFlagVariationKey(
visitorCode,
'my_feature_key',
);
}
init();
import { KameleoonClient, CustomData } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Add CustomData with index `0` containing visitor id to check the targeting
client.addData(new CustomData(0, 'visitor_id'));
// -- Get visitor feature flag variation key
const variationKey = client.getFeatureFlagVariationKey(
visitorCode,
'my_feature_key',
);
}
init();
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode (obligatorio) | string | unique visitor identification string, can’t exceed 255 characters length |
| featureKey (obligatorio) | string | a unique key for feature flag |
Return value
| Tipo | Descripción |
|---|
string | a string containing variable key for the allocated feature flag variation for the provided visitor |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.Initialization | Method was executed before initialize was performed for kameleoonClient. |
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length. |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty. |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found for provided featureKey. |
KameleoonException.FeatureFlagEnvironmentDisabled | Feature flag is disabled for the current environment. |
getVisitorFeatureFlags()
The getVisitorFeatureFlags() method returns a list of feature flags that target a visitor identified by their visitorCode and the feature flags that are active for the specified visitor.
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get active feature flags for visitor
const featureFlags = client.getVisitorFeatureFlags(visitorCode);
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get active feature flags for visitor
const featureFlags = client.getVisitorFeatureFlags(visitorCode);
}
init();
This method only collects the visitor’s active feature flags, meaning the result excludes all feature flags for which the visitor is assigned the off (default or control) variation. When you need all of the visitor’s feature flags, use getFeatureFlags instead.Por ejemplo:// -- `getVisitorFeatureFlags` doesn't trigger feature experiments;
// it only returns feature flags where visitor didn't get the `off` variation
client.getVisitorFeatureFlags('my_visitor').forEach(({ key }) => {
// -- `getFeatureFlagVariationKey` triggers feature experiments,
// as `off` is already filtered out - you won't see a
// visitor taking part in experiment where the `off` variation was allocated.
client.getFeatureFlagVariationKey('my_visitor', key);
});
For cases where you need all of the visitor’s feature flags, use getFeatureFlags instead:// -- Both `off` and other variations are processed as expected
client.getFeatureFlags('my_visitor').forEach(({ key }) => {
client.getFeatureFlagVariationKey('my_visitor', key);
});
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode (obligatorio) | string | unique visitor identification string, can’t exceed 255 characters in length |
Return value
| Tipo | Descripción |
|---|
FeatureFlagType[] | list of feature flags. Each feature flag item contains id and key |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed its initialize call. |
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty. |
KameleoonException.StorageRead | Error while reading storage data. |
getActiveFeatureFlags()
The getActiveFeatureFlags() method returns a Map, where key is featurekey and value is detailed information about the visitor’s variation and it’s variables
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get active feature flags for visitor
// with detailed variation and variables data
const activeFeatures = client.getActiveFeatureFlags(visitorCode);
// -- Result example:
// Map {
// 'feature-key-one' => {
// id: 100,
// key: 'variation-key-one',
// experimentId: 200,
// variables: [
// { key: 'variable_bool', type: VariableType.Boolean, value: true },
// ]
// },
// 'feature-key-two' => {
// id: null, // -> `null` because it is default variation
// key: 'default-variation-key',
// experimentId: null, // -> `null` because it is default variation
// variables: []
// }
// }
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get active feature flags for visitor
// with detailed variation and variables data
const activeFeatures = client.getActiveFeatureFlags(visitorCode);
// -- Result example:
// Map {
// 'feature-key-one' => {
// id: 100,
// key: 'variation-key-one',
// experimentId: 200,
// variables: [
// { key: 'variable_bool', type: VariableType.Boolean, value: true },
// ]
// },
// 'feature-key-two' => {
// id: null, // -> `null` because it is default variation
// key: 'default-variation-key',
// experimentId: null, // -> `null` because it is default variation
// variables: []
// }
// }
}
init();
This method only collects the visitor’s active feature flags. This means the result excludes all the feature flags for which the visitor is assigned to the off (default or control) variation. When you need all of the visitor’s feature flags to iterate, use getFeatureFlags instead.See the getVisitorFeatureFlags CAUTION section method for more details.
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode (obligatorio) | string | unique visitor identification string, can’t exceed 255 characters length |
Return value
| Tipo | Descripción |
|---|
Map<string, KameleoonVariationType> | a map of feature flags, where key is featureKey and value is detailed information about the visitor’s variation and its variables. |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed its initialize call. |
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty. |
KameleoonException.StorageRead | Error while reading storage data. |
KameleoonException.NumberParse | Couldn’t parse Number value. |
KameleoonException.JSONParse | Couldn’t parse JSON value. |
getFeatureFlagVariable()
The getFeatureFlagVariable() method returns a variable for a visitor identified by a visitorCode. This method includes a targeting check that identifies the appropriate variation exposed to the visitor, saves it to storage, and sends a solicitud de seguimiento.
import {
KameleoonClient,
VariableType,
JSONType,
} from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get feature variable
const result = client.getFeatureFlagVariable({
visitorCode,
featureKey: 'my_feature_key'
variableKey: 'my_variable_key'
});
// -- Infer the type of variable by its `type`
switch (result.type) {
case VariableType.BOOLEAN:
const myBool: boolean = result.value;
break;
case VariableType.NUMBER:
const myNum: number = result.value;
break;
case VariableType.JSON:
const myJson: JSONType = result.value;
break;
case VariableType.STRING:
case VariableType.JS:
case VariableType.CSS:
const myStr: string = result.value;
break;
default:
break;
}
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get feature variable
const variableResult = client.getFeatureFlagVariable({
visitorCode,
featureKey: 'my_feature_key'
variableKey: 'my_variable_key'
});
const { type, value } = variableResult;
}
init();
Argumentos
Parameters object of type GetFeatureFlagVariableParamsType containing lo siguiente fields:
| Nombre | Tipo | Descripción |
|---|
| visitorCode (obligatorio) | string | unique visitor identification string, can’t exceed 255 characters in length. |
| featureKey (obligatorio) | string | a unique key for feature flag. |
| variableKey (obligatorio) | string | key of the variable to be found for a feature flag with provided featureKey. Can be found in Kameleoon platform |
Return value
| Tipo | Descripción |
|---|
FeatureFlagVariableType | a variable object containing type and value fields. You can check the type field against VariableType enum. Por ejemplo, if the type is VariableType.BOOLEAN, then value will be a boolean type. |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed its initialize call. |
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty. |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found for provided featureKey. |
KameleoonException.FeatureFlagVariableNotFound | No variable de funcionalidad was found for provided visitorCode and variableKey. |
KameleoonException.FeatureFlagEnvironmentDisabled | Feature flag is disabled for the current environment. |
KameleoonException.JSONParse | Couldn’t parse JSON value. |
KameleoonException.NumberParse | Couldn’t parse Number value. |
getFeatureFlagVariables()
The getFeatureFlagVariables() method returns a variable for a visitor identified by a visitorCode. This method includes a targeting check that identifies the appropriate variation exposed to the visitor, saves it to storage, and sends a solicitud de seguimiento.
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init(): Promise<void> {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get a list of variables for the visitor under `visitorCode` in the feature flag
const variables = client.getFeatureFlagVariables(
visitorCode,
'my_feature_key',
);
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({
siteCode: 'my_site_code',
configuration: { cookieDomain: '.example.com' },
});
async function init() {
await client.initialize();
// -- Get visitor code
const visitorCode = client.getVisitorCode();
// -- Get a list of variables for the visitor under `visitorCode` in the feature flag
const variables = client.getFeatureFlagVariables(
visitorCode,
'my_feature_key',
);
}
init();
Argumentos
| Nombre | Tipo | Descripción |
|---|
| visitorCode (obligatorio) | string | unique visitor identification string, can’t exceed 255 characters. |
| featureKey (obligatorio) | string | a unique key for feature flag. |
Return value
| Tipo | Descripción |
|---|
FeatureVariableResultType[] | a list of variable objects containing key, type and value fields. You can check the type field against VariableType enum. Por ejemplo, if the type is VariableType.BOOLEAN, then value will be a boolean type. |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed its initialize call. |
KameleoonException.VisitorCodeMaxLength | The código de visitante exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The código de visitante is empty. |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found for provided featureKey. |
KameleoonException.FeatureFlagVariationNotFound | No feature variation was found for provided visitorCode and variationKey. |
KameleoonException.FeatureFlagEnvironmentDisabled | Feature flag is disabled for the current environment. |
KameleoonException.JSONParse | Couldn’t parse JSON value. |
KameleoonException.NumberParse | Couldn’t parse Number value. |
onConfigurationUpdate()
Use the onEvent method with EventType.ConfigurationUpdate instead.
The onConfigurationUpdate() method fires a callback on client configuration update.
This method is applicable only for server-sent events used in real-time updates.
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Define logic to be executed on client configuration update
client.onConfigurationUpdate(() => {
// -- My Logic
});
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Define logic to be executed on client configuration update
client.onConfigurationUpdate(() => {
// -- My Logic
});
}
init();
Argumentos
| Nombre | Tipo | Descripción |
|---|
| callback (obligatorio) | () => void | callback function with no parameters that will be called upon configuration update. |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed its initialize call. |
getFeatureFlags()
🚫 Doesn’t send Tracking Data to Kameleoon
The getFeatureFlags() method returns a list of feature flags stored in the client configuration.
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init(): Promise<void> {
await client.initialize();
// -- Get all feature flags
const featureFlags = client.getFeatureFlags();
}
init();
import { KameleoonClient } from '@kameleoon/javascript-sdk';
const client = new KameleoonClient({ siteCode: 'my_site_code' });
async function init() {
await client.initialize();
// -- Get all feature flags
const featureFlags = client.getFeatureFlags();
}
init();
Return value
| Tipo | Descripción |
|---|
FeatureFlagType[] | list of feature flags. Each feature flag item contains an id and key. |
Exceptions thrown
| Tipo | Descripción |
|---|
KameleoonException.Initialization | Method was executed before the kameleoonClient completed its initialize call. |