Mit dem Kameleoon JavaScript SDK können Sie Experiments ausführen und feature flags aktivieren. Die Integration unseres SDK in Ihre Webanwendung ist einfach und sein Footprint (Speicher- und Netzwerknutzung) ist gering.
Erste Schritte: Hilfe für den Einstieg finden Sie im developer guide.
Changelog: Details zur neuesten Version des JavaScript / TypeScript SDK finden Sie im changelog.
SDK Methoden: Die vollständige Referenzdokumentation des JavaScript SDK, see the reference section.
Developer guide
Dieser Abschnitt hilft Ihnen beim Einstieg und stellt Ihnen einige fortgeschrittenere Konzepte vor.
Erste Schritte
Installation
Das Kameleoon SDK Installation-Tool ist die beste Methode, um das SDK schnell zu installieren. Der SDK Installer hilft Ihnen bei der Installation des SDK Ihrer Wahl, beim Generieren eines einfachen Codebeispiels und beim Konfigurieren von externe Abhängigkeiten falls erforderlich.
Um das SDK Installation-Tool zu verwenden, installieren und führen Sie es global aus:
npm install --global @kameleoon/sdk-installer
kameleoon-sdk
Oder führen Sie es direkt mit npx:
npx @kameleoon/sdk-installer
Sie können das JavaScript SDK auch als einzelne Datei mit dem <script> -Tag in Ihre App einbinden. Sie können dann alle SDK-Methoden über das globale Objekt KameleoonSDK.Beispiel:<!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;
To always verwenden Sie neueste Version of a Hauptrelease, verwenden die folgende Skript, wo 4 ist die aktuell major Version:https://static.kameleoon.com/kameleoonSDK-4-latest.js
To always stay on a spezifisch Version, angeben the vollständig Version Zahl stattdessen. Zum Beispiel for Version 4.24.0, das ist die earliest Version verfügbar as a static Skript, verwenden die folgende:https://static.kameleoon.com/kameleoonSDK-4.24.0.js
Versions kann referenced on the Release Seite.Standardmäßig the static Skript verwendet optimized SDK Bundle, wo INFO and DEBUG Log-Nachrichten are removed to reduce Bundle-Größe.Wenn Sie verwenden KameleoonLogger.setLogLevel(LogLevel.DEBUG) or KameleoonLogger.setLogLevel(LogLevel.INFO), verwenden Sie full static Skript stattdessen.https://static.kameleoon.com/kameleoonSDK-4-latest-full.js
https://static.kameleoon.com/kameleoonSDK-4.24.0-full.js
Initialisieren the Kameleoon-Client
Hier ist a Schritt-für-Schritt guide for configuring the JavaScript SDK for your Anwendung.
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) => {});
Um zu starten, developers need to erstellen an Einstiegspunkt for the JavaScript SDK by creating a neu Instanz of Kameleoon-Client.
Verwenden KameleoonClient to run feature Experiments and abrufen der Status of feature flags and their variations.
KameleoonClient initialization is durchgeführt asynchron to ensure that the Kameleoon API call was erfolgreich. For initialization, verwenden die Methode initialize(). Verwenden async/await, Promise.then() or beliebige andere Methode to handle asynchron client initialization.
Arguments
| Name | Typ | Beschreibung |
|---|
| siteCode (required) | string | Dies ist a eindeutig Schlüssel of the Kameleoon project you are using mit das SDK. This Feld is obligatorisch. |
| Konfiguration (optional) | Partial<SDKConfigurationType> | Client’s Konfiguration |
| externals (optional) | ExternalsType | Extern implementation of SDK dependencies (Externe Abhängigkeiten) |
| stubMode (optional) | boolean | Wenn gesetzt auf true, der Client will operate in stub Modus and durchführen no Operationen. In this Modus, alle Methode Aufrufe execute no Aktionen, ensuring that no extern Aktionen or Nebeneffekte occur. |
Konfiguration Parameters
SDK Version 3
SDK Version 4
| Name | Typ | Beschreibung | Standard Wert |
|---|
| updateInterval (optional) | number | Gibt an the refresh Intervall, in Minuten, that das SDK ruft ab die Konfiguration for die aktiven Experiments and feature flags. The Wert bestimmt the maximum time it benötigt to propagate Änderungen, wie zum Beispiel activating or deactivating feature flags or launching Experiments, to your production servers. If nicht angegeben, the Standard Intervall gesetzt ist to 60 Minuten. Zusätzlich we offer a Streaming-Modus that verwendet server-sent Events (SSE) to push neu configurations to das SDK automatically and apply neu configurations in Echtzeit, ohne beliebige delays. | 60 |
| environment (optional) | Environment | feature flag environment | Environment.Production |
| targetingDataCleanupInterval (optional) | number | Intervall in minutes for cleaning up Targeting-Daten, minimum Wert is 1 minute | undefined (no cleanup wird durchgeführt) |
| Domain (optional) | string | Domain to das the Cookie belongs. Veraltet, verwenden cookieDomain stattdessen | undefined |
| cookieDomain (optional) | string | Domain to das the Cookie belongs. | undefined |
| networkDomain (optional) | string | benutzerdefiniert Domain the SDKs verwendet for alle outgoing Netzwerk Anfragen. Commonly verwendet for proxying. The Format is second_level_domain.top_level_domain (zum Beispiel example.com). Wenn ein ungültig Format is angegeben, das SDK verwendet Standard Kameleoon Wert. | undefined |
| requestTimeout (optional) | number | Timeout in milliseconds for alle SDK Netzwerk Anfragen, if Timeout is exceeded Anfrage will fail. | 10_000 (10 Sekunden) |
| trackingInterval (optional) | number | Gibt an das Intervall for Tracking Anfragen in Millisekunden. Alle Besucher der were ausgewertet for beliebige feature flag or had zugeordnete Daten are included in this Tracking Anfrage, das is durchgeführt einmal pro Intervall. The minimum Wert is 100 ms and the maximum Wert is 1_000 ms | 1_000 (1 second) |
The domain Parameter is veraltet and wird removed in a future Release. Verwenden cookieDomain stattdessen.
| Name | Typ | Beschreibung | Standard Wert |
|---|
| updateInterval (optional) | number | Gibt an the refresh Intervall, in Minuten, that das SDK ruft ab die Konfiguration for die aktiven Experiments and feature flags. The Wert bestimmt the maximum time it benötigt to propagate Änderungen, wie zum Beispiel activating or deactivating feature flags or launching Experiments, to your production servers. If nicht angegeben, the Standard Intervall gesetzt ist to 60 Minuten. Zusätzlich we offer a Streaming-Modus that verwendet server-sent Events (SSE) to push neu configurations to das SDK automatically and apply neu configurations in Echtzeit, ohne beliebige delays. | 60 |
| environment (optional) | Environment | string | feature flag environment | Environment.Production |
| targetingDataCleanupInterval (optional) | number | Intervall in minutes for cleaning up Targeting-Daten, minimum Wert is 1 minute | undefined (no cleanup wird durchgeführt) |
| cookieDomain (optional) | string | Domain to das the Cookie belongs. | undefined |
| networkDomain (optional) | string | benutzerdefiniert Domain the SDKs verwendet for alle outgoing Netzwerk Anfragen. Commonly verwendet for proxying. The Format is second_level_domain.top_level_domain (zum Beispiel example.com). Wenn ein ungültig Format is angegeben, das SDK verwendet Standard Kameleoon Wert. | undefined |
| requestTimeout (optional) | number | Timeout in milliseconds for alle SDK Netzwerk Anfragen, if Timeout is exceeded Anfrage will fail immediately | 10_000 (10 Sekunden) |
| trackingInterval (optional) | number | Gibt an das Intervall for Tracking Anfragen in Millisekunden. Alle Besucher der were ausgewertet for beliebige feature flag or had zugeordnete Daten are included in this Tracking Anfrage, das is durchgeführt einmal pro Intervall. The minimum Wert is 1_000 ms and the maximum Wert is 5_000 ms | 1_000 (1 second) |
| defaultDataFile (optional) | string | The defaultDataFile feature ensures the Kameleoon SDK is always READY by providing a fallback Konfiguration wenn no cached data Datei exists. Developers can preload a gültig Konfiguration by fetching it from https://sdk-config.kameleoon.eu/v3/<sitecode> and passing it as defaultDataFile während initialization. Wenn a dateModified timestamp (in Millisekunden) is provided and is newer than the cached Version, das SDK will verwenden Sie Standard datafile anstelle von the cached Version. If dateModified is omitted, the Standard datafile is only applied wenn no cached Version exists. This ensures das SDK always has a gültig Konfiguration, whether Standard, cached, or updated. | undefined |
Option 1 (Empfohlen): Verwenden 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 Zeichenfolge (escape special characters)const configuration = {
updateInterval: 20,
defaultDataFile: `{"configuration":{"consentType":.....,
{"key":"show_car","type":"JSON","value":"{\\"make\\":\\"Porsche\\",\\"model\\":\\"911\\"}"},
"dateModified":1752209266000}`
};
Do not verwenden several client Instanzen in one Anwendung, as es ist not fully unterstützt noch. Several client Instanzen may lead to local storage Konfiguration being overwritten and cause bugs.
Activating a feature flag
Assigning a eindeutig ID to einen Benutzer
To assign a eindeutig ID to einen Benutzer, Sie können verwenden Sie getVisitorCode() Methode. Wenn ein Besucher code doesn’t exist (from die Anfrage headers Cookie), die Methode generates a random eindeutig ID or verwendet a defaultVisitorCode that you would have generated. The ID is then set in a Antwort headers Cookie.
Wenn Sie are using Kameleoon in Hybrid Modus, calling the getVisitorCode() Methode ensures that the eindeutig ID (Besucher code) is shared zwischen die Anwendung Datei engine.js (previously named, kameleoon.js) and das SDK.
Retrieving a flag Konfiguration
To implement a feature flag in your code, Sie müssen first erstellen the feature flag in your Kameleoon account.
To bestimmen der Status or variation of a feature flag for a spezifisch Benutzer, Sie sollten verwenden Sie getVariation() or isFeatureFlagActive() Methode to abrufen die Konfiguration based on the featureKey.
The getVariation() Methode handles both simple feature flags mit ON/OFF states and more complex flags mit mehrere variations. Die Methode retrieves the appropriate variation for den Benutzer by checking the feature Regeln, assigning the variation, and returning it based on the featureKey and visitorCode.
The isFeatureFlagActive() Methode kann verwendet wenn Sie möchten abrufen die Konfiguration of a simple feature flag that has only an ON or OFF state, as opposed to more complex feature flags mit mehrere variations or Targeting options.
If your feature flag has zugeordnet variables (wie zum Beispiel spezifisch behaviors tied to jedes variation) getVariation() also ermöglicht es Ihnen, access the Variation Objekt, das bietet details about the assigned variation and its zugeordnet Experiment. Diese Methode checks whether den Benutzer is targeted, finds den Besucher’s assigned variation, and saves it to storage. Wenn track=true, das SDK will senden the exposure Event to the angegeben Experiment on the next Tracking Anfrage, das is automatically triggered based on das SDK’s tracking_interval_millisecond. Standardmäßig this Intervall gesetzt ist to 1000 Millisekunden (1 second).
The getVariation() Methode ermöglicht es Ihnen, control whether Tracking is done. If track=false, no exposure Events wird sent by das SDK. Dies ist useful if you prefer not to tracken data durch das SDK and stattdessen rely on clientseitig Tracking managed by the Kameleoon engine, for Beispiel. Zusätzlich setting track=false is helpful wenn using the getVariations() Methode, wo you might only need the variations for alle flags ohne triggering beliebige Tracking Events. Wenn Sie möchten know more about how Tracking works, view this article
Adding data points to target einen Benutzer or filter / breakdown visits in reports
To target einen Benutzer, ensure you’ve added relevant data points to their profile vor retrieving the feature variation or checking if the flag ist aktiv. Verwenden Sie addData() Methode to add these data points to den Benutzer’s profile.
Um abzurufen data points collected on andere devices or to access past Benutzer data (collected clientseitig wenn using Kameleoon in Hybrid Modus), verwenden Sie getRemoteVisitorData() Methode. Diese Methode asynchron ruft ab data from the servers. Es ist important to call getRemoteVisitorData() vor retrieving the variation or checking if the feature flag ist aktiv, as this data might be erforderlich to assign einen Benutzer to a given variation.
Um mehr zu erfahren about verfügbar Targeting conditions, see the detailed article on the subject.
Zusätzlich die Daten points you add to den Besucher profile wird verfügbar wenn analyzing your Experiments, allowing you to filter and break down your Ergebnisse by factors like device and browser. Kameleoon Hybrid Modus automatically collects a variety of data points on the clientseitig, making it easy to break down your Ergebnisse based on these pre-collected data points. See the complete Liste here.
If Sie müssen tracken additional data points beyond what’s automatically collected, Sie können verwenden Kameleoon’s Benutzerdefiniert Daten feature. Benutzerdefiniert Daten ermöglicht es Ihnen, capture and analyze spezifisch information relevant to your Experiments. Don’t forget to call the flush() Methode to senden the collected data to Kameleoon-Servern for analysis.
To ensure your Ergebnisse are accurate, it’s empfohlen to filter out bots by using the UserAgent data Typ.
Tracking Ziel Konversionen
Wenn einen Benutzer completes a desired Aktion (wie zum Beispiel making a purchase), es ist recorded as a Konversion. Um zu tracken Konversionen, verwenden Sie trackConversion() Methode and provide the erforderlich visitorCode and goalId Parameter.
The Konversion Tracking Anfrage wird sent along mit the next scheduled Tracking Anfrage, das das SDK sends at regular Intervalle (defined by tracking_interval_millisecond). Wenn Sie prefer to senden die Anfrage immediately, verwenden Sie flush() Methode mit der Parameter instant=true.
Sending Events to analytics solutions
Um zu tracken Konversionen and senden exposure Events to your customer analytics solution, Sie müssen first implement Kameleoon in Hybrid Modus. Then, verwenden Sie getEngineTrackingCode() Methode.
The getEngineTrackingCode() Methode retrieves the eindeutig Tracking code erforderlich to senden exposure Events to your analytics solution. Using diese Methode ermöglicht es Ihnen, record Events and senden them to your desired analytics platform.
Using a benutzerdefiniert bucketing Schlüssel
Standardmäßig Kameleoon verwendet a eindeutig, anonymous Besucher ID (visitorCode) to assign Benutzer to feature flag variations. This ID is typically generated and stored on den Benutzer’s device (in a browser Cookie for clientseitig and serverseitig SDKs—in persistent storage for mobile SDKs). Allerdings in certain scenarios Sie können need to ensure alle Benutzer of die gleiche organization see die gleiche variant of a feature flag.
The Benutzerdefiniert Bucketing Schlüssel option ermöglicht es Ihnen, override this Standard behavior by providing your own benutzerdefiniert identifier for bucketing. This override ensures that Kameleoon’s assignment logic verwendet your angegeben Schlüssel anstelle von the Standard visitorCode.
Verwenden cases
Using a benutzerdefiniert bucketing Schlüssel is essential for maintaining consistency and accuracy in your feature flag assignments, particularly in these situations:
- Account-level or organizational Experiments: For B2B products or scenarios wo you want to assign alle Benutzer from die gleiche organization to die gleiche variation, Sie können verwenden an identifier like an
accountId. Benutzerdefiniert bucketing Schlüssel are crucial for A/B testing features that impact an entire team or company.
By implementing a benutzerdefiniert bucketing Schlüssel, you ensure greater consistency and accuracy in your Experiments, leading to more reliable Ergebnisse and a better Benutzer experience.
Technical details
Wenn you konfigurieren a benutzerdefiniert bucketing Schlüssel for a feature flag, you provide Kameleoon mit a spezifisch identifier from your Anwendung’s data:
client.addData(visitorCode, new CustomData(index, 'newVisitorCode'));
- Providing the benutzerdefiniert Schlüssel: You provide your benutzerdefiniert identifier to the Kameleoon SDK using the
addData() Methode. In diese Methode, Sie werden pass your chosen benutzerdefiniert bucketing Schlüssel as a CustomData Objekt. Here, newVisitorCode refers to the identifier you wish to verwenden for your bucketing (zum Beispiel the neu userId or accountId).
For the benutzerdefiniert bucketing Schlüssel to Funktion correctly, it must also be defined and configured for the feature flag während the flag creation or editing process. Ohne this corresponding Konfiguration, das SDK’s bucketing will not apply your benutzerdefiniert Schlüssel. For detailed instructions on how to set this up in Kameleoon, refer to this article.
- Bucketing logic: Einmal a benutzerdefiniert bucketing Schlüssel is provided durch the
addData() Methode, alle hash calculations for assigning Benutzer to variations will verwenden this newVisitorCode (your benutzerdefiniert Schlüssel) anstelle von the Standard visitorCode. Using the newVisitorCode means that the bucketing decision is tied to your benutzerdefiniert identifier, ensuring consistent assignments across various contexts wo that identifier is present.
- Daten Tracking and analytics: It’s crucial to beachten Sie, dass while the
newVisitorCode (your benutzerdefiniert Schlüssel) is verwendet for bucketing decisions, alle subsequent data (Tracking Events and Konversionen, for Beispiel) is sent and zugeordnet zu the original visitorCode. This separation ensures that your analytics accurately reflect individual Benutzer journeys and interactions innerhalb your Experiment’s broader context, even wenn bucketing is durchgeführt at a higher level (like an account) or across mehrere devices/Sitzungen. Your original Besucher data remains intact for comprehensive reporting.
Technical requirementes
To effectively verwenden a benutzerdefiniert bucketing Schlüssel:
- The Schlüssel muss a
string.
- It muss eindeutig for the entity you intend to bucket (zum Beispiel if using a
userId, jedes Benutzer’s ID sollte eindeutig).
- The Schlüssel muss verfügbar to das SDK at the exact moment the feature flag decision is ausgewertet for that Benutzer or Anfrage.
Targeting conditions
The Kameleoon SDKs support a variety of predefined Targeting conditions that Sie können verwenden to target Benutzer in your campaigns.
For die Liste of conditions unterstützt by dieses SDK, see verwenden visit history to target Benutzer.
Sie können auch verwenden your own extern data to target Benutzer.
Logging
Das SDK generates logs to reflect various internal processes and issues.
Log levels
Das SDK unterstützt 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);
Benutzerdefiniert handling of logs
Das SDK writes its logs to the console output standardmäßig. This behaviour kann overridden.
Logging limiting by a log level is durchgeführt apart from the log handling logic.
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);
Domain information
You provide a Domain as the domain in the KameleoonClient Konfiguration, das is verwendet for storing Kameleoon Besucher code in Cookies. Domains are important wenn working mit the getVisitorCode and setLegalConsent Methoden. The Domain you provide is stored in the Cookie as the Domain= Schlüssel.
Setting die Domain
The Domain you provide zeigt an if die URL address can verwenden Sie Cookie. Zum Beispiel if your Domain is www.example.com. the Cookie is only verfügbar from a www.example.com URL. This means Seiten mit the app.example.com Domain can’t verwenden Sie Cookie.
For more fllexibility mit subdomains, Sie können angeben die Domain mit a period (.). Zum Beispiel die Domain .example.com ermöglicht the Cookie to Funktion on both app.example.com and login.example.com.
Sie können’t verwenden regular expressions, special symbols, protocol, or port Zahlen in the domain.
Zusätzlich a spezifisch Liste of subdomains can’t be verwendet mit the prefix ..
Here’s a small Domain cheat sheet:
| 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 |
Developing on localhost
localhost is always considered a bad Domain, making testing die Domain wenn developing on localhost difficult.
Es gibt two ways to avoid this issue:
- Don’t angeben the
domain Feld in das SDK client while testing.
- Erstellen a local Domain for
localhost. Zum Beispiel:
- Navigate to
/etc/hosts on Linux or to c:\Windows\System32\Drivers\etc\hosts on Windows.
- Open
hosts mit Datei super Benutzer or administrator rights.
- Add a Domain to the
localhost port, for Beispiel: 127.0.0.1 app.com
- Now Sie können run your app locally on
app.com:{my_port} and angeben .app.com as your Domain
Externe Abhängigkeiten
SDK externe Abhängigkeiten verwenden Sie dependency injection pattern to give you the ability to provide your own implementations for certain parts of ein SDK.
In the JavaScript SDK, alle externe Abhängigkeiten have Standard implementations, das verwenden a native browser API so there’s no need to provide them unless ein anderes API ist erforderlich for spezifisch verwenden cases.
Here’s die Liste of verfügbar externe Abhängigkeiten:
| Dependency | Interface | Erforderlich/Optional | API Used | Beschreibung |
|---|
storage | IExternalStorage | Optional | Browser localStorage | Used for storing alle the existing and collected SDK data. |
requester | IExternalRequester | Optional | Browser fetch | Used for performing alle Netzwerk Anfragen. |
eventSource | IExternalEventSource | Optional | Browser EventSource | Used for receiving Server Sent Events for Real Time Aktualisieren capabilities. |
visitorCodeManager | IExternalVisitorCodeManager | Optional | Browser Cookie | Used for storing and synchronizing Besucher codes. |
logger | ILogger | Optional | Benutzerdefiniert implementation | Used for benutzerdefiniert handling of logs from das SDK. Lets you define how logs are processed and their output. |
Die folgende Beispiel implements externe Abhängigkeiten. To import an interface from ein SDK, erstellen a class that implements the interface and pass the instantiated class to das SDK.
Storage
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(),
},
});
Fehler Handling
Almost every KameleoonClient Methode may throw ein Fehler occassionaly. These Fehler are deliberately predefined KameleoonErrors
that extend the native JavaScript Error class, providing useful Nachrichten and special type Felder mit a Typ KameleoonException.
KameleoonException ist ein enum containing alle possible Fehler Typen.
To know exactly what Typ of KameleoonException die Methode may throw, prüfen the Throws section in die Methode Beschreibung on this Seite, or hover over die Methode in your IDE to see the jsdocs Beschreibung.
Handling Fehler makes your Anwendung 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();
Cross-device experimentation
To support Besucher der access an app from mehrere devices, Kameleoon ermöglicht the synchronization of previously collected Besucher data across jedes of den Besucher’s devices and reconciliation of their visit history across devices durch cross-device experimentation. Case studies and detailed information on how Kameleoon handles data across devices sind verfügbar in the article on cross-device experimentation.
Synchronizing benutzerdefiniert data across devices
Although benutzerdefiniert mapping synchronization is verwendet to align Besucher data across devices, es ist not always necessary. Below are two scenarios wo benutzerdefiniert mapping sync is not erforderlich:
Same Benutzer ID across devices
If die gleiche Benutzer ID is verwendet consistently across alle devices, synchronization is handled automatically ohne a benutzerdefiniert mapping sync. Es ist enough to call the getRemoteVisitorData() Methode wenn you want to sync die Daten collected zwischen mehrere devices.
Multi-server Instanzen mit consistent IDs
In complex setups involving mehrere servers (zum Beispiel distributed server Instanzen), wo die gleiche Benutzer ID ist verfügbar across servers, synchronization zwischen servers (mit getRemoteVisitorData()) is sufficient ohne additional benutzerdefiniert mapping sync.
Customers der need additional data can refer to the getRemoteVisitorData() Methode Beschreibung for further guidance. In the below code, es ist assumed that die gleiche eindeutig identifier (in this case, the visitorCode, das can also be referred to as userId) is verwendet consistently zwischen the two devices for accurate data retrieval.
Wenn Sie möchten sync collected data in Echtzeit, Sie müssen choose the scope Besucher for your benutzerdefiniert data.
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();
Using benutzerdefiniert data for Sitzung merging
SDK Version 3
SDK Version 4
Cross-device experimentation ermöglicht es Ihnen, combine einen Besucher’s history across jedes of their devices (history reconciliation). History reconciliation ermöglicht es Ihnen, merge different Besucher Sitzungen into ein einzelnes Sitzung. To reconcile visit history, verwenden CustomData to provide a eindeutig identifier for den Besucher.Follow the activating cross-device history reconciliation guide to einrichten your benutzerdefiniert data in Kameleoon.Wenn your benutzerdefiniert data gesetzt ist up, Sie können verwenden it in your code to merge einen Besucher’s Sitzungen. Sitzungen mit die gleiche identifier will always see die gleiche Experiment variation, and are displayed as ein einzelnes Besucher in the Visitor view of your Experiment’s Ergebnis Seite.Das SDK Konfiguration ensures that zugeordnet Sitzungen always see die gleiche variation of the Experiment.Afterwards, Sie können verwenden das SDK normally. Die folgende Methoden may be helpful mit Sitzung merging:
getRemoteVisitorData mit isUniqueIdentifier=true - to abrufen data for alle linked Besucher
trackConversion or flush mit isUniqueIdentifier=true - to tracken data for a spezifisch Besucher that is zugeordnet zu ein anderes Besucher.
Here’s an Beispiel of how to verwenden benutzerdefiniert data for Sitzung merging.In this Beispiel, we have an Anwendung mit a login Seite. Since we don’t know den Benutzer ID at the moment of login, we verwenden an anonymous Besucher identifier generated by thegetVisitorCode Methode. Nach den Benutzer logs in, we can associate the anonymous Besucher mit den Benutzer ID and verwenden it as den Besucher’s eindeutig 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 ermöglicht for combining einen Besucher’s history across jedes of their devices (history reconciliation). History reconciliation allow merging different Besucher Sitzungen into one. To reconcile visit history, verwenden CustomData to provide a eindeutig identifier for den Besucher. Weitere Informationen, see the dedicated documentation.Nach cross-device reconciliation ist aktiviert, calling getRemoteVisitorData() mit der Parameter userId retrieves alle known data for a given Benutzer.Sitzungen mit die gleiche identifier will always be shown die gleiche variation in an Experiment. In the Besucher view of your Experiment’s Ergebnisse Seiten, these Sitzungen will appear as ein einzelnes Besucher.Das SDK Konfiguration ensures that zugeordnet Sitzungen always see die gleiche variation of the Experiment. Allerdings es gibt einige limitations regarding cross-device variation allocation. These limitations are outlined here.Follow the activating cross-device history reconciliation guide to einrichten your benutzerdefiniert data on the Kameleoon platform.Afterwards, Sie können verwenden das SDK normally. Die folgende Methoden that may be helpful in the context of Sitzung merging:
getRemoteVisitorData() mit added UniqueIdentifier(true) - to abrufen data for alle linked Besucher.
trackConversion() or flush() mit added UniqueIdentifier(true) data - to tracken einige data for spezifisch Besucher that is zugeordnet zu ein anderes Besucher.
Here’s an Beispiel of how to verwenden benutzerdefiniert data for Sitzung 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();
Utilities
Das SDK has a set of utility Methoden that Sie können verwenden to simplify your development process. Alle Methoden are represented as static members of KameleoonUtils class.
simulateSuccessRequest
Verwenden Sie simulateSuccessRequest Methode to simulate a erfolgreich Anfrage to the Kameleoon server. It kann useful for benutzerdefiniert Requester implementations, wenn a developer needs to simulate a erfolgreich Anfrage (zum Beispiel 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);
}
}
Arguments
| Name | Typ | Beschreibung |
|---|
| requestType (required) | RequestType | A Typ of Anfrage |
| data (required) | SimulateRequestDataType[RequestType] | A Typ of Anfrage data, das is different depending on RequestType |
Daten Typ SimulateRequestDataType ist definiert as follows:
RequestType.Tracking - null
RequestType.ClientConfiguration - ClientConfigurationDataType
RequestType.RemoteData - JSONType
Zurückgeben Wert
| Typ | Beschreibung |
|---|
Promise<KameleoonResponseType> | gibt einen promise mit die Antwort of die Anfrage |
getCookieValue
Verwenden Sie getCookieValue Methode to parse a common Cookie Zeichenfolge (key_1=value_1; key_2=value_2; ...) and get der Wert of a spezifisch Cookie Schlüssel. Diese Methode is useful wenn working mit a benutzerdefiniert 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`
Arguments
| Name | Typ | Beschreibung |
|---|
| Cookie (required) | string | Cookie Zeichenfolge in a form key_1=value_1; key_2=value_2 |
| Schlüssel (required) | string | Zeichenfolge representation of einen Schlüssel to find a Wert by |
Zurückgeben Wert
| Typ | Beschreibung | |
|---|
| `string | null` | gibt einen Zeichenfolge mit a Cookie Wert or null if der Schlüssel was not found |
Referenz
Dies ist the vollständig reference documentation for the Kameleoon JavaScript SDK.
Initialization
initialisieren()
SDK Version 3
SDK Version 4
initialize() ist ein asynchron Methode for KameleoonClient initialization. Die Methode ruft ab Kameleoon SDK data from our servers or retrieves data from a local source if data is up-to-date or the aktualisieren Intervall has not been reached.
-
If das SDK Konfiguration could not be retrieved but es gibt an older Konfiguration verfügbar in das SDK storage, das SDK verwendet older Konfiguration as a fallback and
initialize does not throw ein Fehler.
-
Client initialization has an optional offline mode.
Es ist activated by setting the optional
useCache Parameter to true.
In offline mode, if Tracking Anfragen for beliebige of die folgende Methoden fail due to internet connectivity issues, das SDK automatically resends die Anfrage wenn internet connection wurde 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();
Arguments
| Name | Typ | Beschreibung | Standard Wert |
|---|
| useCache (optional) | boolean | Parameter for activating SDK offline Modus. If true, failed polls will not zurückgeben Fehler and will verwenden cached data if such data ist verfügbar. | false |
Zurückgeben Wert
| Typ | Beschreibung |
|---|
Promise<boolean> | A promise that resolves to a boolescher Wert indicating whether das SDK was successfully initialized. Usually, if an unresolvable issue occurs, the initialize Methode will throw ein Fehler anstelle von resolving the promise. Daher the boolean Wert is almost always true and typically does not provide much additional information. |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.StorageWrite | Couldn’t aktualisieren storage data |
KameleoonException.ClientConfiguration | Couldn’t abrufen client Konfiguration from Kameleoon API |
KameleoonException.MaximumRetriesReached | Maximum retries reached, Anfrage failed |
An asynchron Methode 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 aktualisieren Intervall has not been reached.
-
If das SDK Konfiguration could not be retrieved but es gibt an older Konfiguration verfügbar in SDK storage, das SDK verwendet older Konfiguration as a fallback and the
initialize does not throw ein Fehler.
-
SDK unterstützt an offline mode.
In offline mode if Tracking Anfragen from beliebige of die folgende Methoden fail due to internet connectivity issues, das SDK automatically resends die Anfrage as soon as it detects that the internet connection wurde 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();
Zurückgeben Wert
| Typ | Beschreibung |
|---|
Promise<boolean> | A promise that resolves to a boolescher Wert indicating whether das SDK was successfully initialized. Usually, if an unresolvable issue occurs, the initialize Methode will throw ein Fehler anstelle von resolving the promise. Daher the boolean Wert is almost always true and typically does not provide much additional information. |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.StorageWrite | Couldn’t aktualisieren storage data |
KameleoonException.ClientConfiguration | Couldn’t abrufen client Konfiguration from Kameleoon API |
KameleoonException.MaximumRetriesReached | Maximum retries reached, Anfrage failed |
Feature flags and variations
getVariation()
- 📨 Sends Tracking Daten to Kameleoon (depending on the
track Parameter)
Retrieves the Variation assigned to a given Besucher for a spezifisch feature flag.
Diese Methode benötigt featureKey as a obligatorisch argument and track as an optional argument. The track argument ist optional and defaults to true.
It gibt zurück assigned Variation for den Besucher. If den Besucher is not zugeordnet zu beliebige feature flag Regeln, die Methode gibt zurück Standard Variation for the given feature flag.
Ensure that proper Fehler handling is implemented in your code to manage potential Ausnahmen.
The Standard variation refers to the variation assigned to einen Besucher wenn they do not match beliebige predefined delivery Regeln for a feature flag. In andere words, it ist die fallback variation applied to alle Benutzer der are not targeted by spezifisch Regeln. 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();
Arguments
An Objekt of Typ GetVariationParamsType mit die folgende Eigenschaften:
| Name | Typ | Beschreibung | Standard |
|---|
| visitorCode (required) | string | Eindeutig identifier of den Besucher. | |
| featureKey (required) | string | Schlüssel of the feature you want to expose to einen Besucher. | |
| tracken (optional) | boolean | An optional Parameter to aktivieren or deaktivieren Tracking of the feature evaluation. | true |
Zurückgeben Wert
| Typ | Beschreibung |
|---|
Variation | An assigned Variation to a given Besucher for a spezifisch feature flag. |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Methode was executed vor the kameleoonClient completed it’s initialize call. |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer. |
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length (255 characters). |
KameleoonException.FeatureFlagConfigurationNotFound | Ausnahme indicating that the requested feature Schlüssel wasn’t found in the internal Konfiguration of das SDK. This usually means that the feature flag is not activated in the Kameleoon app (but code implementing the feature is bereits deployed in die Anwendung). |
KameleoonException.FeatureFlagEnvironmentDisabled | Ausnahme indicating that feature flag ist deaktiviert for den Besucher’s aktuell environment (zum Beispiel production, staging, or development). |
getVariations()
- 📨 Sends Tracking Daten to Kameleoon (depending on the
track Parameter)
- 🎯 Events:
EventType.Evaluation
Retrieves a map of Variation Objekte assigned to a given Besucher across alle feature flags.
Diese Methode iterates over alle verfügbar feature flags and gibt zurück assigned Variation for jedes flag zugeordnet zu the angegeben Besucher. It benötigt visitorCode as a obligatorisch argument, while onlyActive and track sind optional.
- If
onlyActive gesetzt ist to true, die Methode getVariations() will zurückgeben feature flags variations provided den Benutzer is not bucketed mit the off variation.
- The
track Parameter controls whether or not die Methode will tracken the variation assignments. Standardmäßig it gesetzt ist to true. Wenn gesetzt to false, the Tracking wird deaktiviert.
The returned map consists of feature flag Schlüssel as Schlüssel and their corresponding Variation as Werte. Wenn kein variation is assigned for a feature flag, die Methode gibt zurück Standard Variation for that flag.
Proper Fehler handling sollte implemented to manage potential Ausnahmen.
The Standard variation refers to the variation assigned to einen Besucher wenn they do not match beliebige predefined delivery Regeln for a feature flag. In andere words, it ist die fallback variation applied to alle Benutzer der are not targeted by spezifisch Regeln. 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();
Arguments
An Objekt of Typ GetVariationParamsType mit die folgende Eigenschaften:
| Name | Typ | Beschreibung | Standard |
|---|
| visitorCode (required) | string | Eindeutig identifier of den Besucher. | |
| onlyActive (optional) | boolean | An optional Parameter indicating whether to zurückgeben variations for aktiv (true) or alle (false) feature flags. | false |
| tracken (optional) | boolean | An optional Parameter to aktivieren or deaktivieren Tracking of the feature evaluation. | true |
Zurückgeben Wert
| Typ | Beschreibung |
|---|
Map<string, Variation> | Map that enthält the assigned Variation Objekte of the feature flags using the Schlüssel of the corresponding features. |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Methode was executed vor the kameleoonClient completed it’s initialize call. |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer. |
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length (255 characters). |
isFeatureFlagActive()
- 📨 Sends Tracking Daten to Kameleoon (depending on the
track Parameter)
- 🎯 Events:
EventType.Evaluation
Die Methode isFeatureFlagActive() gibt einen boolescher Wert Wert indicating whether den Besucher identified by visitorCode has the angegeben featureKey aktiv. Diese Methode checks for Targeting, bestimmt the variation for den Besucher, and saves this information to storage. Zusätzlich it sends a Tracking Anfrage.
Es gibt also an overload of diese Methode that ermöglicht es Ihnen, pass a track Parameter, das Sie können verwenden to deaktivieren Tracking of the feature evaluation.
Only Besucher mit an aktiv feature flag muss targetted.
Kameleoon verwendet Tracking to count Sitzungen and Besucher wenn you call certain Methoden, wie zum Beispiel isFeatureFlagActive(), getVariation() or getVariations().Verwenden Sie Standard true Wert for the track Parameter wenn you expose Besucher to a variation and need to count them. Set the track Parameter to false only if you call these Methoden vor you expose Besucher.Zum Beispiel if you call getVariations() to abrufen alle variations vor you expose Besucher, set the track Parameter to false. This setting prevents Kameleoon from prematurely counting a Sitzung. Sie können then trigger Tracking later wenn you explicitly expose den Besucher.Kameleoon sends Tracking data every second standardmäßig. Sie können konfigurieren this Intervall up to five Sekunden using the Tracking Intervall Konfiguration option. Kameleoon groups Tracking Events into ein einzelnes Sitzung as long as das Intervall zwischen Events is less than 30 Minuten. If more than 30 Minuten elapse zwischen Tracking Events, Kameleoon counts the Events as separate Sitzungen. A visit appears in your reports 30 Minuten nach the last recorded Event in the Sitzung.
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() Methode evaluates the served variant, not the master flag state. Wenn Sie exclude Regeln, die Methode verwendet Then, for everyone else serve Standard state. Wenn Sie select Off for this Standard state, die Methode always returns false even wenn the master feature flag is On.
Arguments
Es gibt two overloads verfügbar for diese Methode:
- Two Parameter overload:
This overload is veraltet and wird removed in the next major aktualisieren. Please verwenden Sie neu overload mit an Objekt Parameter.
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | eindeutig Besucher identification Zeichenfolge, can’t exceed 255 characters in length |
| featureKey (required) | string | a eindeutig Schlüssel for feature flag |
- Objekt Parameter overload of Typ
IsFeatureFlagActiveParamsType:
| Name | Typ | Beschreibung | Standard |
|---|
| visitorCode (required) | string | eindeutig Besucher identification Zeichenfolge, can’t exceed 255 characters in length | - |
| featureKey (required) | string | a eindeutig Schlüssel for feature flag | - |
| tracken (optional) | boolean | a boolescher Wert indicator of whether to tracken the feature evaluation | true |
Zurückgeben Wert
| Typ | Beschreibung |
|---|
boolean | a boolescher Wert indicating whether the feature flag mit featureKey ist aktiv for den Besucher mit visitorCode |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Methode was executed vor the kameleoonClient completed its initialize call. |
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer. |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found for provided featureKey. |
KameleoonException.DataInconsistency | Allocated variation was found, but es gibt no feature flag mit according featureKey |
setForcedVariation()
Die Methode ermöglicht es Ihnen, programmatically assign a spezifisch Variation to einen Benutzer, bypassing the standard evaluation process. Dies ist especially valuable for controlled Experiments wo the usual evaluation logic is not erforderlich or muss skipped. It can also be helpful in scenarios like debugging or benutzerdefiniert testing.
Wenn a forced variation gesetzt ist, it overrides Kameleoon’s Echtzeit evaluation logic. Processes like segmentation, Targeting conditions, and algorithmic calculations are skipped. To preserve segmentation and Targeting conditions während an Experiment, set forceTargeting=false stattdessen.
Simulated variations always nehmen precedence in the execution order. Wenn ein simulated variation calculation is triggered, it wird fully processed and completed first.
A forced variation is treated die gleiche as an ausgewertet variation. Es ist getrackt in analytics and stored in den Benutzer context like beliebige standard ausgewertet variation, ensuring consistency in reporting.
Die Methode may throw Ausnahmen under certain conditions (e.g., ungültig Parameter, Benutzer context, or internal issues). Proper Ausnahme handling is essential to ensure that your Anwendung remains stable and resilient.
It’s important to distinguish forced variations from simulated variations:
- Forced variations: Are spezifisch to an individual Experiment.
- Simulated variations: Affect the overall feature flag Ergebnis.
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();
Arguments
An Objekt of Typ SetForcedVariationParametersType mit die folgende Eigenschaften:
| Name | Typ | Beschreibung | Standard | |
|---|
| visitorCode (required) | string | Eindeutig identifier of den Besucher. | | |
| experimentId (required) | number | Experiment Id that wird targeted and selected während the evaluation process. | | |
| variationKey (required) | `string | null` | Variation Schlüssel corresponding to a Variation that sollte forced as the returned Wert for the Experiment. If der Wert is null, the forced variation wird reset. | |
| forceTargeting (optional) | boolean | Zeigt an whether Targeting for the Experiment sollte forced and skipped (true) or applied as in the standard evaluation process (false). | true | |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeEmpty | The Besucher code is leer. |
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length (255 characters). |
KameleoonException.Initialization | Zeigt an that das SDK is noch nicht fully initialized. |
KameleoonException.FeatureFlagExperimentNotFound | Ausnahme indicating that the requested Experiment id has not been found in das SDK’s internal Konfiguration. Dies ist usually normal and means that the Regel’s corresponding Experiment has noch nicht been activated on Kameleoon’s side. |
KameleoonException.FeatureFlagVariationNotFound | Ausnahme indicating that the requested variation Schlüssel(id) has not been found in the internal Konfiguration of das SDK. Dies ist usually normal and means that the variation’s corresponding Experiment has noch nicht been activated on Kameleoon’s side. |
KameleoonException.StorageRead | Couldn’t lesen storage data. |
KameleoonException.StorageWrite | Couldn’t aktualisieren storage data. |
In most cases, only the basic Fehler, KameleoonException, needs to be handled, as demonstrated in das Beispiel. Allerdings if different Typen of Fehler require a Antwort, handle jedes one separately based on spezifisch requirements. Zusätzlich for enhanced reliability, general language Fehler kann handled by including Error.
evaluateAudiences()
- 📨 Sends Tracking Daten to Kameleoon
Diese Methode evaluates Besucher against alle verfügbar Audiences Explorer Segmente and tracks those der match.
evaluateAudiences() sollte aufgerufen nach alle relevant Besucher data wurde set or updated, and just vor getting a feature variation or checking a feature flag. This approach ensures that den Besucher is ausgewertet against the most aktuell data verfügbar, allowing for accurate audience assignment based on alle criteria.
Nach calling diese Methode, Sie können durchführen 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();
Arguments
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | Eindeutig identifier of den Besucher. |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Methode was executed vor the kameleoonClient completed it’s initialize call. |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer. |
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length (255 characters). |
In most cases, only the basic Fehler, KameleoonException, needs to be handled, as demonstrated in das Beispiel. Allerdings if different Typen of Fehler require a Antwort, handle jedes one separately based on spezifisch requirements. Zusätzlich for enhanced reliability, general language Fehler kann handled by including Error.
getDataFile()
To auswerten alle feature flags, verwenden getVariations(). Diese Methode is more efficient than calling DataFile and iterating durch flags mit getVariation().
Gibt zurück aktuell SDK Konfiguration as a DataFile Objekt.
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();
Zurückgeben Wert
| Typ | Beschreibung |
|---|
DataFile | The DataFile containing das SDK Konfiguration |
Besucher data
getVisitorCode()
The getVisitorCode() Methode obtains einen Besucher code from der Browser Cookie. If den Besucher code doesn’t exist, die Methode generates a random Besucher code (or verwendet defaultVisitorCode Wert if you provided one) and sets the neu Besucher code in a Cookie.
The getVisitorCode() Methode ermöglicht es Ihnen, set simulated variations for einen Besucher. Wenn Cookies (from a Anfrage or document) contain der Schlüssel kameleoonSimulationFFData, the standard evaluation process is bypassed. Stattdessen, die Methode directly gibt einen Variation based on the provided data.Sie können apply simulations in two ways:
- Automatically (empfohlen): If using Kameleoon Web Experimentation or das SDK in Hybrid Modus, the Cookie is erstellt automatically wenn 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 Ergebnis.
- Forced variations: Are spezifisch to an individual Experiment.
⚙️ Manual setupPlease ensure the kameleoonSimulationFFData Cookie follows this Format:
kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simulates the variation mit varId of Experiment expId for the given featureKey.
kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simulates the Standard variation (defined in the Then, for everyone else in Production, serve section) for the given featureKey.
⚠️ To ensure proper functionality, the Cookie Wert muss encoded as a URI component using a Methode wie zum Beispiel 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();
Arguments
| Name | Typ | Beschreibung |
|---|
defaultVisitorCode (optional) | string | Besucher code verwendet if es gibt no Besucher code in Cookies |
Wenn Sie don’t provide a defaultVisitorCode and es gibt no Besucher code stored in a Cookie, den Besucher code wird randomly generated.
Zurückgeben Wert
| Typ | Beschreibung |
|---|
string | Ergebnis Besucher code |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | The Besucher code length was exceeded |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer |
addData()
The addData() Methode adds Targeting-Daten to storage so andere Methoden can verwenden die Daten to decide whether to target the aktuell Besucher.
The addData() Methode does not zurückgeben beliebige Wert and does not interact mit Kameleoon back-end servers on its own. Stattdessen, alle the declared data is saved for future transmission using the flush Methode. This approach reduces die Zahl of server Aufrufe made, as die Daten is typically grouped into ein einzelnes server call. Beachten Sie, dass the trackConversion Methode also sends out beliebige previously zugeordnete Daten, just like the flush Methode. The same is true for the getFeatureFlagVariationKey and getFeatureFlagVariable Methoden, if an experimentation Regel is triggered.
Jedes Besucher can only have one Instanz of zugeordnete Daten for most data Typen. Allerdings CustomData ist ein Ausnahme. Visitors can have one Instanz of zugeordnet CustomData pro customDataIndex.
-
userAgent data will not be stored in storage like andere data, and it wird sent mit every Tracking Anfrage for bot filtration.
-
For die Daten Typen Sie können verwenden for Targeting, see the unterstützt 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();
Arguments
| Name | Typ | Beschreibung | Standardwert |
|---|
| visitorCode (required) | string | eindeutig Besucher identification Zeichenfolge, can’t exceed 255 characters. | |
| tracken (optional) | boolean | Gibt an whether the added data is eligible for Tracking. Wenn gesetzt auf false, die Daten is stored locally and verwendet only for Targeting evaluation; es ist not sent to the Kameleoon Daten API. | true |
| kameleoonData (optional) | KameleoonDataType[] | Zahl of Instanzen of beliebige Typ of KameleoonData, kann added solely in Array or as sequential arguments | |
-
kameleoonData ist ein variadic argument. It kann passed as one or several arguments (see das Beispiel).
-
The index or ID of the benutzerdefiniert data kann found in your Kameleoon account. Beachten Sie, dass this index starts at
0, das means that the first benutzerdefiniert data you erstellen for a given site wird assigned 0 as its ID, not 1.
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length of 255 characters. |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer. |
KameleoonException.StorageWrite | Couldn’t aktualisieren storage data. |
KameleoonException.Initialization | Methode was executed vor the kameleoonClient completed its initialize call. |
Prüfen the Daten Types reference weitere Details on how to manage different data Typen.
flush()
SDK Version 3
SDK Version 4
The flush() Methode collects the Kameleoon data linked to den Besucher. It then sends a Tracking Anfrage, along mit alle data added using the addData Methode, das has noch nicht been sent using eines von these Methoden.Wenn Sie don’t angeben a visitorCode, das SDK flushes alle of its stored data to the remote Kameleoon-Servern. If beliebige previously failed Tracking Anfragen were stored locally in offline Modus, das SDK attempts to senden the stored Anfragen vor executing die neueste Anfrage.The isUniqueIdentifier kann helpful in eindeutig situations; zum Beispiel if you cannot access the anonymous visitorCode given to einen Besucher, but Sie können verwenden an internal ID linked to that Besucher durch Sitzung 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();
Arguments
| Name | Typ | Beschreibung | Standard |
|---|
| visitorCode (optional) | string | eindeutig Besucher identification Zeichenfolge, can’t exceed 255 characters, falls nicht passed, alle data wird flushed (sent to the remote Kameleoon-Servern). | - |
| isUniqueIdentifier (optional) | boolean | an optional Parameter for specifying if the visitorCode ist ein eindeutig identifier. | false |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer. |
KameleoonException.Initialization | Methode was executed vor the kameleoonClient completed its initialize call. |
flush() benötigt the Kameleoon data zugeordnet zu einen Besucher and schedules die Daten to be sent in the next Tracking Anfrage. The time of the next Tracking Anfrage ist definiert by das SDK Konfiguration trackingInterval Parameter. Besucher data kann added using the addData and getRemoteVisitorData Methoden.Wenn Sie don’t angeben a visitorCode, das SDK flushes alle of its stored data to the remote Kameleoon-Servern. If beliebige previously failed Tracking Anfragen were stored locally in offline Modus, das SDK attempts to senden the stored Anfragen vor executing die neueste Anfrage.If Sie müssen senden Tracking Anfragen immediately, verwenden flushInstant() — the asynchron Version of flush that returns Promise<void>. Sie können await it wenn you need delivery guarantees (zum Beispiel vor Seite navigation/unload), or call it ohne await as a fire-and-forget Anfrage:
await client.flushInstant(visitorCode) sends Tracking Anfragen immediately for a spezifisch Besucher and waits for completion
await client.flushInstant() sends Tracking Anfragen immediately for alle Besucher 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();
Arguments
| Name | Typ | Beschreibung | Standard |
|---|
| visitorCode (optional) | string | eindeutig Besucher identification Zeichenfolge, can’t exceed 255 characters, falls nicht passed, alle data wird flushed (sent to the remote Kameleoon-Servern). | - |
Or an Objekt mit der Typ FlushParamsType, containing:| Name | Typ | Beschreibung | Standard |
|---|
| visitorCode (optional) | string | eindeutig Besucher identification Zeichenfolge, can’t exceed 255 characters, falls nicht passed, alle data wird flushed (sent to the remote Kameleoon-Servern). | - |
| instant (optional) | boolean | Boolescher Wert flag indicating whether die Daten sollte sent instantly (true) or entsprechend the scheduled Tracking Intervall (false). | - |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer. |
KameleoonException.Initialization | Methode was executed vor the kameleoonClient completed it’s initialize call. |
getRemoteData()
The getRemoteData() Methode returns data that is stored for a angegeben site code in a remote Kameleoon server.
Sie können verwenden diese Methode to abrufen Benutzer preferences, historical data, or beliebige andere data relevant to your Anwendung’s logic. By storing this data on our highly scalable servers using our Daten API, Sie können efficiently manage massive amounts of data and abrufen it for jedes of your Besucher or Benutzer.
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();
Arguments
| Name | Typ | Beschreibung |
|---|
| Schlüssel (required) | string | eindeutig Schlüssel mit das data is zugeordnet. |
Zurückgeben Wert
| Typ | Beschreibung |
|---|
JSONType | promise mit data retrieved for a spezifisch Schlüssel |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.RemoteData | Couldn’t abrufen data from the Kameleoon server. |
getRemoteVisitorData()
SDK Version 3
SDK Version 4
getRemoteVisitorData() ist ein asynchron Methode verwendet to abrufen Kameleoon Visits Daten for the visitorCode from the Kameleoon Daten API. Diese Methode stores data for making Targeting decisions.Daten obtained using diese Methode is important wenn you want to:
- verwenden data collected from andere devices.
- access einen Benutzer’s history, wie zum Beispiel previously visited Seiten während past visits.
- verwenden data that is only accessible on the clientseitig, like datalayer variables and Ziele that only convert on the front-end.
Lesen this article for a better understanding of possible verwenden cases.The isUniqueIdentifier kann helpful in eindeutig situations; zum Beispiel if you cannot access the anonymous visitorCode given to einen Besucher, but Sie können verwenden an internal ID linked to that Besucher durch Sitzung 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();
Arguments
An Objekt mit der Typ RemoteVisitorDataParamsType containing:| Name | Typ | Beschreibung | Standard Wert |
|---|
| visitorCode (required) | string | eindeutig Besucher identification Zeichenfolge, can’t exceed 255 characters. | - |
| shouldAddData (optional) | boolean | boolescher Wert flag identifying whether the retrieved benutzerdefiniert data sollte added to storage automatically (ohne calling the addData Methode afterwards). | true |
| filters (optional) | VisitorDataFiltersType | filters for specifying what data sollte retrieved from visits, standardmäßig only customData is retrieved from the aktuell and latest vorherig visit. | { previousVisitAmount: 1, currentVisit: true customData: true }, andere filters Parameter are gesetzt auf false |
| isUniqueIdentifier (optional) | boolean | optional Parameter that, wenn true, gibt an that the visitorCode ist ein eindeutig identifier. | false |
Zurückgeben Wert
| Typ | Beschreibung |
|---|
KameleoonDataType[] | promise mit Liste of Kameleoon Daten retrieved |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer |
KameleoonException.RemoteData | Couldn’t abrufen data from Kameleoon server |
KameleoonException.VisitAmount | Visit amount muss a Zahl zwischen 1 and 25 |
KameleoonException.Initialization | Methode was executed vor initialize was done for kameleoonClient |
Using Parameter in getRemoteVisitorData()
The getRemoteVisitorData() Methode offers flexibility by allowing you to define various Parameter wenn retrieving data on Besucher. Whether you’re Targeting based on Ziele, Experiments, or variations, die gleiche approach applies across alle data Typen.Zum Beispiel wenn Sie möchten abrufen data on Besucher der completed a Ziel “Order transaction”, Sie können angeben Parameter innerhalb the getRemoteVisitorData() Methode to refine your Targeting. For Instanz, wenn Sie möchten target only Benutzer der converted on the Ziel in their last five visits, die Sie festlegen können the previousVisitAmount Parameter to 5 and conversions to true.The flexibility shown in this Beispiel is not limited to Ziel data. Sie können verwenden Parameter innerhalb the getRemoteVisitorData() Methode to abrufen data on a variety of Besucher behaviors.Hier ist die Liste of verfügbar VisitorDataFiltersType filters:| Name | Typ | Beschreibung | Standard |
|---|
| previousVisitAmount (optional) | number | Zahl of vorherig visits to abrufen data from. Zahl zwischen 1 and 25 | 1 |
| currentVisit (optional) | boolean | If true, aktuell visit data wird retrieved | true |
| customData (optional) | boolean | If true, benutzerdefiniert data wird retrieved. | true |
| pageViews (optional) | boolean | If true, Seite data wird retrieved. | false |
| geolocation (optional) | boolean | If true, geolocation data wird retrieved. | false |
| device (optional) | boolean | If true, device data wird retrieved. | false |
| browser (optional) | boolean | If true, browser data wird retrieved. | false |
| operatingSystem (optional) | boolean | If true, operating system data wird retrieved. | false |
| Konversionen (optional) | boolean | If true, Konversion data wird retrieved. | false |
| Experiments (optional) | boolean | If true, Experiment data wird retrieved. | false |
| kcs (optional) | boolean | If true, Kameleoon Konversion Score (KCS) wird retrieved. Erfordert the AI Predictive Targeting add-on | false |
getRemoteVisitorData() ist ein asynchron Methode for retrieving Kameleoon Visits Daten for the visitorCode from the Kameleoon Daten API. Die Methode adds data to storage for andere Methoden to verwenden wenn making Targeting decisions.Daten obtained using dies ist important wenn you want to:
- verwenden data collected from andere devices.
- access einen Benutzer’s history, wie zum Beispiel previously visited Seiten während past visits.
- verwenden data that is only accessible on the clientseitig, like datalayer variables and Ziele that only convert on the front-end.
Lesen this article for a better understanding of possible verwenden 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();
Arguments
An Objekt mit der Typ RemoteVisitorDataParamsType containing:| Name | Typ | Beschreibung | Standard Wert |
|---|
| visitorCode (required) | string | eindeutig Besucher identification Zeichenfolge, can’t exceed 255 characters length | - |
| shouldAddData (optional) | boolean | boolescher Wert flag identifying whether the retrieved benutzerdefiniert data sollte added to storage automatically (ohne calling the addData Methode afterwards) | true |
| filters (optional) | VisitorDataFiltersType | filters for specifying what data sollte retrieved from visits, standardmäßig only customData is retrieved from the aktuell and latest vorherig visit | { previousVisitAmount: 1, currentVisit: true customData: true }, andere filters Parameter are gesetzt auf false |
Zurückgeben Wert
| Typ | Beschreibung |
|---|
KameleoonDataType[] | promise mit Liste of Kameleoon Daten retrieved |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer |
KameleoonException.RemoteData | Couldn’t abrufen data from Kameleoon server |
KameleoonException.VisitAmount | Visit amount muss a Zahl zwischen 1 and 25 |
KameleoonException.Initialization | Methode was executed vor initialize was done for kameleoonClient |
Using Parameter in getRemoteVisitorData()
The getRemoteVisitorData() Methode offers flexibility, allowing you to define various Parameter wenn retrieving data on Besucher. Whether you’re Targeting based on Ziele, Experiments, or variations, die gleiche approach applies across alle data Typen.Zum Beispiel wenn Sie möchten abrufen data on Besucher der completed a Ziel “Order transaction”, Sie können angeben Parameter innerhalb the getRemoteVisitorData() Methode to refine your Targeting. For Instanz, wenn Sie möchten target only Benutzer der converted on the Ziel in their last five visits, die Sie festlegen können the previousVisitAmount Parameter to 5 and conversions to true.The flexibility shown in this Beispiel is not limited to Ziel data. Sie können verwenden Parameter innerhalb the getRemoteVisitorData() Methode to abrufen data on a variety of Besucher behaviors.Hier ist die Liste of verfügbar VisitorDataFiltersType filters:| Name | Typ | Beschreibung | Standard |
|---|
| previousVisitAmount (optional) | number | Zahl of vorherig visits to abrufen data from. Zahl zwischen 1 and 25 | 1 |
| currentVisit (optional) | boolean | If true, aktuell visit data wird retrieved | true |
| customData (optional) | boolean | If true, benutzerdefiniert data wird retrieved. | true |
| pageViews (optional) | boolean | If true, Seite data wird retrieved. | false |
| geolocation (optional) | boolean | If true, geolocation data wird retrieved. | false |
| device (optional) | boolean | If true, device data wird retrieved. | false |
| browser (optional) | boolean | If true, browser data wird retrieved. | false |
| operatingSystem (optional) | boolean | If true, operating system data wird retrieved. | false |
| Konversionen (optional) | boolean | If true, Konversion data wird retrieved. | false |
| Experiments (optional) | boolean | If true, Experiment data wird retrieved. | false |
| kcs (optional) | boolean | If true, Kameleoon Konversion Score (KCS) wird retrieved. Erfordert the AI Predictive Targeting add-on | false |
| visitorCode (optional) | boolean | If true, Kameleoon will abrufen the visitorCode from the most recent visit and verwenden it for the aktuell visit. Dies ist necessary wenn Sie möchten ensure that den Besucher, identified by their visitorCode, always receives die gleiche variation across visits for Cross-device experimentation. | true |
| personalization (optional) | boolean | If true, personalization data wird retrieved. This ist erforderlich for the personalization condition | false |
| cbs (optional) | boolean | If true, Contextual Bandit score data wird retrieved. | false |
getVisitorWarehouseAudience()
getVisitorWarehouseAudience ist ein asynchron Methode that retrieves alle audience data zugeordnet zu den Besucher in your data warehouse using the angegeben visitorCode and warehouseKey. The warehouseKey is typically your internal Benutzer ID. The customDataIndex Parameter corresponds to the Kameleoon benutzerdefiniert data that Kameleoon verwendet to target your Besucher. 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();
Arguments
Parameters Objekt consisting of:
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | eindeutig Besucher identification Zeichenfolge, can’t exceed 255 characters length |
| customDataIndex (required) | number | Zahl representing the index of the benutzerdefiniert data you want to verwenden to target your Warehouse Audiences |
| warehouseKey (optional) | string | eindeutig Schlüssel to identify the warehouse data (usually, your internal Benutzer ID) |
Zurückgeben Wert
| Typ | Beschreibung |
|---|
Promise<CustomData | null> | promise containing CustomData mit the zugeordnet warehouse data or null if there was no data |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer |
KameleoonException.RemoteData | Couldn’t abrufen data from Kameleoon server |
setLegalConsent()
Consent information is synchronized zwischen the Kameleoon Engine (Anwendung Datei engine.js) and the JS SDK. This synchronization means that einmal consent gesetzt ist on either the Engine or das SDK, it’s automatically set for both. This feature eliminates the need for manual consent handling and ensures that SDKs operate in compliance mit Benutzer preferences.Wenn Sie verwenden Kameleoon in Hybrid Modus, we recommend reading the consent section in our Hybrid experimentation article
Wenn handling legal consent, it’s important to verwenden Sie getVisitorCode Methode from KameleoonClient, not the veraltet Methode from KameleoonUtils. Zusätzlich diese Methode does not accept domain as an argument. Stattdessen, pass it to the KameleoonClient constructor. Refer to the above Beispiel.
The setLegalConsent Methode gibt an whether den Besucher has given legal consent to verwenden personal data. Setting the legalConsent Parameter to false limits the Typen of data that Sie können include in Tracking Anfragen. Diese Methode hilft Ihnen, adhere to legal and regulatory requirements while responsibly managing Besucher data. Sie können find weitere Informationen 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();
Arguments
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | eindeutig Besucher identification Zeichenfolge, can’t exceed 255 characters. length |
| consent (required) | boolean | a boolescher Wert Wert representing the legal consent Status. true zeigt an that den Besucher has given legal consent. false zeigt an that den Besucher has never provided or has withdrawn legal consent. |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | The Besucher code length exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer |
Consent revocation behavior
Wenn you call setLegalConsent() mit consent=false, das SDK does not delete the kameleoonVisitorCode Cookie. Stattdessen, 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 Datei upon opt-out, Sie müssen delete it manually using your framework’s native Cookie management Methoden. Das SDK will not entfernen die Datei automatically.
Ziele and Drittanbieter- analytics
trackConversion()
SDK Version 3
SDK Version 4
- _📨 Sends Tracking Daten to Kameleoon
Verwenden diese Methode to tracken a Konversion for a spezifisch Ziel and Benutzer. Diese Methode erfordert visitorCode and goalId. Zusätzlich diese Methode also accepts an optional revenue argument. The visitorCode is usually identical to the one that was verwendet wenn triggering the Experiment.The trackConversion() Methode doesn’t zurückgeben beliebige Wert. Diese Methode is non-blocking as der Server call is made asynchron.Wenn Sie angeben a visitorCode and set isUniqueIdentifier to true, the trackConversion() Methode verwendet it as the eindeutig Besucher identifier, das is useful for cross-device experimentation weil das SDK links the flushed data mit den Besucher that is zugeordnet zu the angegeben identifier.The isUniqueIdentifier can also be useful in andere edge-case scenarios, wie zum Beispiel wenn Sie können’t access the anonymous visitorCode that was originally assigned to den Besucher, but you do have access to an internal ID that is connected to the anonymous Besucher using Sitzung 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();
Arguments
Parameters Objekt consisting of:| Name | Typ | Beschreibung | Standard |
|---|
| visitorCode (required) | string | Eindeutig identifier of den Besucher. | |
| goalId (required) | number | ID of the Ziel. | |
| revenue (optional) | number | Revenue of the Konversion. | 0 |
| isUniqueIdentifier (optional) | boolean | An optional Parameter for specifying if the visitorCode ist ein eindeutig identifier. | false |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer. |
KameleoonException.StorageWrite | Couldn’t aktualisieren storage data. |
- 📨 Sends Tracking Daten to Kameleoon
Verwenden diese Methode to tracken a Konversion for a spezifisch Ziel and Benutzer. Diese Methode erfordert visitorCode and goalId. Zusätzlich diese Methode also accepts an optional revenue, negative and metadata arguments. The visitorCode is usually identical to the one that was verwendet wenn triggering the Experiment.The trackConversion() Methode doesn’t zurückgeben beliebige Wert. Diese Methode is non-blocking as der Server call is made asynchron.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();
Arguments
Parameters Objekt consisting of:| Name | Typ | Beschreibung | Standard |
|---|
| visitorCode (required) | string | Eindeutig identifier of den Besucher. | |
| goalId (required) | number | ID of the Ziel. | |
| negative (optional) | boolean | Definiert if the revenue is positive or negative. | false |
| revenue (optional) | number | Revenue of the Konversion. | 0 |
| metadata (optional) | CustomData[] | Metadata of the Konversion. Muss defined beforehand in the Kameleoon App. | undefined |
metadata Werte are accessible durch raw data exports and the Ergebnisse Seite.Wenn das metadata Parameter is provided, Kameleoon will verwenden these angegeben Werte for the aktuell Konversion anstelle von what was previously collected using the addData() Methode. If der Parameter is omitted, Kameleoon will verwenden Sie last getrackt Werte for those CustomData prior to the Konversion and innerhalb die gleiche visit.Kameleoon will only consider the metadata Werte that are explicitly passed as Parameter to the trackConversion() Methode.In das Beispiel below, Kameleoon will associate the Konversion only mit the benutzerdefiniert data Wert explicitly provided as a Parameter (here: index 5 mit der Wert ‘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
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer. |
KameleoonException.StorageWrite | Couldn’t aktualisieren storage data. |
getEngineTrackingCode()
Kameleoon integrates mit several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. Um zu tracken serverseitig Experiments correctly, call the getEngineTrackingCode() Methode nach den Besucher triggers an Experiment. Das SDK returns JavaScript queue commands for the Experiments that den Besucher triggered während the vorherig five Sekunden. Wenn you insert this code into die Seite, Engine.js processes the commands and sends the exposure Events durch die aktiven analytics integration.
Refer to hybrid experimentation weitere Informationen on implementing diese Methode.
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 verwenden this feature, implement both the JavaScript SDK and Kameleoon Engine.js. Weil Engine.js is verwendet only for Tracking in this flow, Sie können install the asynchron tag vor the closing
</body> tag.
-
Sie können 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>
In this Beispiel, 123456 and 234567 are Experiment IDs, and 7890 and 8901 are variation IDs. In your implementation, das SDK generates these Werte in the returned Tracking code.
Arguments
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | Eindeutig identifier of den Besucher. |
Zurückgeben Wert
| Typ | Beschreibung |
|---|
string | JavaScript code to insert into die Seite. |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | The Besucher code length exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer. |
Events
SDK Version 3
SDK Version 4
Kameleoon offers built-in integrations mit various analytics and CDP solutions, wie zum Beispiel Mixpanel, Google Analytics 4, Segment…. To ensure that Sie können tracken and analyze your serverseitig Experiments, Kameleoon bietet a Methode, getEngineTrackingCode(), that gibt zurück JavasScript code to be inserted in your Seite. The code automatically sends the exposure Events to your analytics solution. Das SDK builds a Tracking code for your aktiv analytics solution based on the Experiments that den Besucher has triggered in the last five Sekunden.
Weitere Informationen about hybrid experimentation, please refer to this article.The getEngineTrackingCode() Methode gibt zurück Kameleoon Tracking code for the aktuell Besucher. The Tracking code is based on the Experiments that were triggered während the last five Sekunden.To benefit from this feature, Sie werden need to implement both the JavaScript SDK and our Kameleoon JavaScript tag. We recommend you implement the Kameleoon asynchron tag, das Sie können install vor closing the <body> tag in your HTML Seite, as it will only be verwendet for Tracking purposes.
onEvent()
Methode onEvent() fires a Callback wenn a spezifisch Event is triggered. The Callback Funktion can access die Daten zugeordnet zu das Event.
Das SDK Methoden in this documentation note das Event Typen they trigger, if beliebige.Sie können only assign one Callback to jedes 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 sind definiert in the EventType enum. Depending on das Event Typ, the eventData Parameter will have a different Typ.| Typ | eventData Typ | Beschreibung |
|---|
EventType.Evaluation | EvaluationEventDataType | Triggered wenn das SDK evaluates beliebige variation for a feature flag. Es ist triggered regardless of das Ergebnis variation. |
EventType.ConfigurationUpdate | ConfigurationUpdateEventDataType | Triggered wenn das SDK receives a Konfiguration aktualisieren from der Server (wenn using Echtzeit Streaming). |
Arguments
| Name | Typ | Beschreibung |
|---|
| Event (required) | EventType | a Typ of das Event to associate mit the Callback. |
| Callback (required) | (eventData: EventDataType<EventType>) => void | a Callback Funktion mit the eventData Parameter that is aufgerufen wenn a Konfiguration aktualisieren occurs. |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Methode was executed vor the kameleoonClient completed the initialize call. |
Sending exposure Events to extern tools
Kameleoon offers built-in integrations mit various analytics and CDP solutions, wie zum Beispiel Mixpanel, Google Analytics 4, Segment…. To ensure that Sie können tracken and analyze your serverseitig Experiments, Kameleoon bietet a Methode, getEngineTrackingCode(), that gibt zurück JavasScript code to be inserted in your Seite. The code automatically sends the exposure Events to your analytics solution. Das SDK builds a Tracking code for your aktiv analytics solution based on the Experiments that den Besucher has triggered in the last five Sekunden.
Weitere Informationen about hybrid experimentation, please refer to this article.The getEngineTrackingCode() Methode gibt zurück Kameleoon Tracking code for the aktuell Besucher. The Tracking code is based on the Experiments that were triggered während the last five Sekunden.To benefit from this feature, Sie werden need to implement both the JavaScript SDK and our Kameleoon JavaScript tag. We recommend you implement the Kameleoon asynchron tag, das Sie können install vor closing the <body> tag in your HTML Seite, as it will only be verwendet for Tracking purposes.
Daten Typen
Kameleoon Daten Typen are helper classes verwendet to store data in storage in predefined forms.
Während the flush execution, das SDK collects alle data and sends it mit the Tracking Anfrage.
Daten verfügbar in das SDK is not verfügbar for Targeting and reporting in the Kameleoon app until you add die Daten (zum Beispiel by using the addData() methodt).
See verwenden visit history to target Benutzer weitere Informationen.
Wenn Sie are using hybrid Modus, call getRemoteVisitorData() to automatically fill alle data that Kameleoon has previously collected.
Browser
Since JavaScript SDK 4.10.0, Browser is automatically detected based on the User-Agent Zeichenfolge. Allerdings Sie können still manually override it falls erforderlich.
Browser enthält browser information.
Jedes Besucher can only have one Browser. Adding second a Browser overwrites the first one.
| Name | Typ | Beschreibung |
|---|
| browser (required) | BrowserType | predefined browser Typ (Chrome, InternetExplorer, Firefox, Safari, Opera, Other). |
| Version (optional) | number | Version of der Browser, floating point Zahl repräsentiert major and minor Version of der 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 verwendet as marker for eindeutig Besucher identification.
Wenn Sie add UniqueIdentifier for einen Besucher, visitorCode is verwendet as the eindeutig Besucher identifier, das is useful for Cross-device experimentation. Associating a UniqueIdentifier mit einen Besucher notifies das SDK that den Besucher is linked to ein anderes Besucher.
The isUniqueIdentifier kann helpful in eindeutig situations; zum Beispiel if you cannot access the anonymous visitorCode given to einen Besucher, but Sie können verwenden an internal ID linked to that Besucher durch Sitzung merging.
Jedes Besucher can only have one UniqueIdentifier. Adding ein anderes UniqueIdentifier overwrites the first one.
| Name | Typ | Beschreibung |
|---|
| Wert (required) | boolean | Wert that gibt an if den Besucher is zugeordnet zu ein anderes Besucher, false implies that den Besucher is not zugeordnet zu beliebige andere Besucher. |
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();
Konversion
The Conversion data set stored here kann verwendet to filter Experiment and personalization reports by beliebige Ziel zugeordnet zu it.
- Jedes Besucher can have mehrere
Conversion Objekte.
- Sie können find the
goalId in the Kameleoon app.
ConversionParametersType conversionParameters - an Objekt mit Konversion Parameter described below
| Name | Typ | Beschreibung | Standard |
|---|
| goalId (required) | number | ID of the Ziel. | |
| revenue (optional) | float | Revenue of the Konversion | 0 |
| negative (optional) | boolean | Definiert if the revenue is positive or negative. | false |
| metadata (optional) | CustomData[] | Metadata of the Konversion. | 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 enthält information about the Cookie stored on den Besucher’s device.
-
Generally, the JavaScript SDK will attempt to verwenden a
localStorage Cookie for the conditions. If localStorage is not possible, das SDK can verwenden Cookie data as an alternative.
-
Jedes Besucher can only have one
Cookie. Adding a second Cookie overwrites the first one.
| Name | Typ | Beschreibung |
|---|
| Cookie (required) | CookieType[] | A Liste of CookieType Objekte consisting of Cookie Schlüssel and Werte. |
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 Methode, fromString, that Sie können verwenden to erstellen a Cookie by parsing a Zeichenfolge that enthält gültig Cookie data.
Die Methode accepts string as a Parameter and gibt einen initialized Cookie Instanz.
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 enthält den Besucher’s geolocation details.
Jedes Besucher can only have one GeolocationData. Adding a second GeolocationData overwrites the first one.
An Objekt Parameter mit der Typ GeolocationInfoType enthält die folgende Felder:
| Name | Typ | Beschreibung |
|---|
| country (required) | string | The country of den Besucher. |
| region (optional) | string | The region of den Besucher. |
| city (optional) | string | The city of den Besucher. |
| postalCode (optional) | string | The postal code of den Besucher. |
| coordinates (optional) | [number, number] | Coordinates Array tuple of two location Werte (latitude and longitude). Coordinate Zahl repräsentiert 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 ermöglicht beliebige Typ of data to be easily zugeordnet zu jedes Besucher. It can then be verwendet as a Targeting condition in Segmente or as a filter/breakdown in Experiment reports.
Um mehr zu erfahren about benutzerdefiniert data, please refer to this article.
| Name | Typ | Beschreibung | Standard |
|---|
| index/Name (required) | number/string | Index or Name of the benutzerdefiniert data. Either index or name muss provided to identify die Daten. | |
| overwrite (optional) | boolean | Flag to explicitly control how die Werte are stored and how they appear in reports. See more | true |
| Wert (required) | string[] | The benutzerdefiniert data Wert. It muss stringified to match the string Typ. Note: Wert is variadic. | |
-
Jedes Besucher is allowed only one
CustomData for jedes eindeutig index. Adding ein anderes CustomData mit die gleiche index will replace the existing one.
-
The benutzerdefiniert data ‘index’ finden Sie im Benutzerdefiniert Daten dashboard under the “INDEX” column.
-
To prevent das SDK from sending data mit the selected index to Kameleoon-Servern for privacy reasons, aktivieren the option: Verwenden this data only locally for Targeting purposes wenn creating benutzerdefiniert data.
-
Adding a
CustomData Instanz erstellt mit a Name wenn das SDK Instanz is not initialized or der Name is not registered, will Ergebnis in die Daten 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 Zeichenfolge. Allerdings Sie können still manually override it falls erforderlich.
Device enthält information about your device.
Jedes Besucher can have only one Device. Adding a second Device overwrites the first one.
| Name | Typ | Beschreibung |
|---|
| deviceType (required) | DeviceType | possible Typen for device Typ (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 Zeichenfolge. Allerdings Sie können still manually override it falls erforderlich.
OperatingSystem enthält information about the operating system on den Besucher’s device.
Jedes Besucher can only have one OperatingSystem. Adding a second OperatingSystem overwrites the first one.
| Name | Typ | Beschreibung |
|---|
| operatingSystem (required) | OperatingSystemType | possible Typen for device Typ: 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. Allerdings Sie können still manually override it falls erforderlich.
PageView enthält information about your web Seite.
Jedes Besucher can have one PageView pro eindeutig URL. Adding a second PageView mit die gleiche URL notifies das SDK that den Besucher re-visited die Seite.
PageViewParametersType pageViewParameters - an Objekt mit Seite view Parameter described below
| Name | Typ | Beschreibung |
|---|
| urlAddress (required) | string | url address of die Seite to tracken. |
| title (required) | string | title of the web Seite. |
| referrer (optional) | number[] | an optional Parameter containing a Liste of referrer indices, has no Standardwert. |
Sie können find the index or referrer ID in your Kameleoon account. Beachten Sie, dass this index starts at 0, meaning the first acquisition channel you erstellen for a given site wird 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 ermöglicht es Ihnen, store information on den Besucher’s Benutzer-agent. Server-side Experiments are more likely to be affected by bot traffic than clientseitig Experiments. Kameleoon verwendet IAB/ABC International Spiders and Bots Liste to tackle this issue and recognize known bots and spiders. Kameleoon also verwendet UserAgent Feld to filter out bots and andere unwanted traffic that might distort your Konversion metrics. Weitere Details, see our help article on bot filtering.
Wenn Sie verwenden internal bots, we suggest that you pass der Wert 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.
| Name | Typ | Beschreibung |
|---|
| Wert (required) | string | Wert verwendet for comparison |
Wenn Sie run Kameleoon in an hybrid Modus, your feature Experiments are automatically protected against bot traffic. This protection occurs weil Kameleoon collects den Benutzer-agent automatically on the front-end. Daher you don’t need to pass den Benutzer-agent or beliebige andere Parameter to filter bots and spiders.Wenn Sie verwenden internal bots, we suggest that you pass der Wert 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 repräsentiert the semantic Version Zahl of your Anwendung.
A Besucher can have only one ApplicationVersion. Adding a second Instanz will overwrite the first one.
| Name | Typ | Beschreibung |
|---|
| Version (optional) | string | The mobile Anwendung Version. This Feld must follow semantic versioning. Accepted Formate 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();
Returned Types
DataFile
The DataFile enthält das SDK Konfiguration details.
It kann extended mit additional information if erforderlich by clients. Wenn Sie need weitere Details, please contact your Customer Success Manager.
| Name | Typ | Beschreibung |
|---|
| featureFlags | Map<string, FeatureFlag> | A map of FeatureFlag Objekte, keyed by feature flag Schlüssel. |
| dateModified | number | The timestamp (in Millisekunden) indicating wenn 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 repräsentiert a set of Eigenschaften that define a feature flag itself — zum Beispiel its Variations, Rules, environment Status, and andere related details.
It kann extended mit additional information if erforderlich by clients. Wenn Sie need weitere Details, please contact your Customer Success Manager.
| Name | Typ | Beschreibung |
|---|
| environmentEnabled | boolean | Indicating whether the feature flag ist aktiviert in the aktuell environment. |
| defaultVariationKey | string | The Schlüssel of the Standard variation zugeordnet zu the feature flag. |
| variations | Map<string, Variation> | A map of Variation Objekte, keyed by variation Schlüssel. |
| Regeln | Rule[] | A Liste of Rule Objekte |
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;
Regel
The Rule repräsentiert a set of Eigenschaften that define a Regel itself — zum Beispiel its Variations.
It kann extended mit additional information if erforderlich by clients. Wenn Sie need weitere Details, please contact your Customer Success Manager.
| Name | Typ | Beschreibung |
|---|
| variations | Map<string, Variation> | A map of Variation Objekte, keyed by variation Schlüssel. |
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 enthält information about the assigned variation to den Besucher (or the Standard variation, wenn kein spezifisch assignment exists).
| Name | Typ | Beschreibung |
|---|
| Name | string | Name of the variation. |
| Schlüssel | string | Schlüssel of the variation. |
| id | number or null | id of the variation or null if den Besucher landed on the Standard variation. |
| experimentId | number or null | id of the Experiment or null if den Besucher landed on the Standard variation. |
| variables | Map<string, Variable> | map of variables for the variation, wo Schlüssel ist die variable Schlüssel and Wert ist die variable Objekt. |
- Ensure that your code handles the case wo
id or experimentId is null, indicating a Standard variation.
- The
variables map might be leer wenn kein variables are zugeordnet zu 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 enthält information about a variable zugeordnet zu the assigned variation.
| Name | Typ | Beschreibung |
|---|
| Schlüssel | string | The eindeutig Schlüssel identifying the variable. |
| Typ | string | The Typ of the variable. Possible Werte: BOOLEAN, NUMBER, STRING, JSON, JS, CSS. |
| Wert | any | The Wert of the variable, das kann of die folgende Typen: boolescher Wert, Zahl, Zeichenfolge, Record<Zeichenfolge, beliebige>, beliebige[]. |
// 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 || '';
Veraltet Methoden
These Methoden are veraltet and wird removed in the next major aktualisieren.
getFeatureFlagVariationKey()
The getFeatureFlagVariationKey() Methode retrieves the variation Schlüssel for einen Besucher identified by a visitorCode. Diese Methode umfasst a Targeting prüfen that identifies the appropriate variation exposed to den Besucher, saves it to storage, and sends a Tracking Anfrage.
Wenn einen Benutzer is not zugeordnet zu a feature flag, das SDK randomly gibt einen variation Schlüssel entsprechend the feature flag Regeln. If den Benutzer has bereits been registered mit the feature flag, das SDK will detect this association and zurückgeben den Benutzer’s vorherig variation Schlüssel Wert. Allerdings if den Benutzer does not meet beliebige of the defined Regeln, das SDK will zurückgeben der Standardwert angegeben in Kameleoon’s feature flag delivery Regeln. It’s important to beachten Sie, dass der Standardwert kann a variation Schlüssel, a boolescher Wert Wert, or ein anderes data Typ, depending on the feature flag’s Konfiguration.
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();
Arguments
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | eindeutig Besucher identification Zeichenfolge, can’t exceed 255 characters length |
| featureKey (required) | string | a eindeutig Schlüssel for feature flag |
Zurückgeben Wert
| Typ | Beschreibung |
|---|
string | a Zeichenfolge containing variable Schlüssel for the allocated feature flag variation for the provided Besucher |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Methode was executed vor initialize was durchgeführt for kameleoonClient. |
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length. |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer. |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found for provided featureKey. |
KameleoonException.FeatureFlagEnvironmentDisabled | Feature flag ist deaktiviert for the aktuell environment. |
getVisitorFeatureFlags()
- 🚫 Doesn’t senden Tracking Daten to Kameleoon
- 🎯 Events:
EventType.Evaluation (for jedes feature flag)
The getVisitorFeatureFlags() Methode gibt einen Liste of feature flags that target einen Besucher identified by their visitorCode and the feature flags that are aktiv for the angegeben Besucher.
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();
Diese Methode only collects den Besucher’s active feature flags, meaning das Ergebnis excludes alle feature flags for das den Besucher is assigned the off (Standard or control) variation. Wenn you need alle of den Besucher’s feature flags, verwenden getFeatureFlags stattdessen.Zum Beispiel:// -- `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 wo you need alle of den Besucher’s feature flags, verwenden getFeatureFlags stattdessen:// -- Both `off` and other variations are processed as expected
client.getFeatureFlags('my_visitor').forEach(({ key }) => {
client.getFeatureFlagVariationKey('my_visitor', key);
});
Arguments
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | eindeutig Besucher identification Zeichenfolge, can’t exceed 255 characters in length |
Zurückgeben Wert
| Typ | Beschreibung |
|---|
FeatureFlagType[] | Liste of feature flags. Jedes feature flag item enthält id and key |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Methode was executed vor the kameleoonClient completed its initialize call. |
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer. |
KameleoonException.StorageRead | Fehler while reading storage data. |
getActiveFeatureFlags()
- 🚫 Doesn’t senden Tracking Daten to Kameleoon
- 🎯 Events:
EventType.Evaluation (for jedes feature flag)
The getActiveFeatureFlags() Methode gibt einen Map, wo Schlüssel is featurekey and Wert is detailed information about den Besucher’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();
Diese Methode only collects den Besucher’s active feature flags. This means das Ergebnis excludes alle the feature flags for das den Besucher is assigned to the off (Standard or control) variation. Wenn you need alle of den Besucher’s feature flags to iterate, verwenden getFeatureFlags stattdessen.See the getVisitorFeatureFlags CAUTION section Methode weitere Details.
Arguments
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | eindeutig Besucher identification Zeichenfolge, can’t exceed 255 characters length |
Zurückgeben Wert
| Typ | Beschreibung |
|---|
Map<string, KameleoonVariationType> | a map of feature flags, wo key is featureKey and value is detailed information about den Besucher’s variation and its variables. |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Methode was executed vor the kameleoonClient completed its initialize call. |
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer. |
KameleoonException.StorageRead | Fehler while reading storage data. |
KameleoonException.NumberParse | Couldn’t parse Zahl Wert. |
KameleoonException.JSONParse | Couldn’t parse JSON Wert. |
getFeatureFlagVariable()
The getFeatureFlagVariable() Methode gibt einen variable for einen Besucher identified by a visitorCode. Diese Methode umfasst a Targeting prüfen that identifies the appropriate variation exposed to den Besucher, saves it to storage, and sends a Tracking Anfrage.
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();
Arguments
Parameters Objekt of Typ GetFeatureFlagVariableParamsType containing die folgende Felder:
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | eindeutig Besucher identification Zeichenfolge, can’t exceed 255 characters in length. |
| featureKey (required) | string | a eindeutig Schlüssel for feature flag. |
| variableKey (required) | string | Schlüssel of the variable to be found for a feature flag mit provided featureKey. Kann found in Kameleoon platform |
Zurückgeben Wert
| Typ | Beschreibung |
|---|
FeatureFlagVariableType | a variable Objekt containing type and value Felder. Sie können prüfen the type Feld against VariableType enum. Zum Beispiel if the type is VariableType.BOOLEAN, then value wird a boolean Typ. |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Methode was executed vor the kameleoonClient completed its initialize call. |
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer. |
KameleoonException.FeatureFlagConfigurationNotFound | No feature flag was found for provided featureKey. |
KameleoonException.FeatureFlagVariableNotFound | No feature variable was found for provided visitorCode and variableKey. |
KameleoonException.FeatureFlagEnvironmentDisabled | Feature flag ist deaktiviert for the aktuell environment. |
KameleoonException.JSONParse | Couldn’t parse JSON Wert. |
KameleoonException.NumberParse | Couldn’t parse Zahl Wert. |
getFeatureFlagVariables()
The getFeatureFlagVariables() Methode gibt einen variable for einen Besucher identified by a visitorCode. Diese Methode umfasst a Targeting prüfen that identifies the appropriate variation exposed to den Besucher, saves it to storage, and sends a Tracking Anfrage.
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();
Arguments
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | eindeutig Besucher identification Zeichenfolge, can’t exceed 255 characters. |
| featureKey (required) | string | a eindeutig Schlüssel for feature flag. |
Zurückgeben Wert
| Typ | Beschreibung |
|---|
FeatureVariableResultType[] | a Liste of variable Objekte containing key, type and value Felder. Sie können prüfen the type Feld against VariableType enum. Zum Beispiel if the type is VariableType.BOOLEAN, then value wird a boolean Typ. |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Methode was executed vor the kameleoonClient completed its initialize call. |
KameleoonException.VisitorCodeMaxLength | The Besucher code exceeded the maximum length (255 characters). |
KameleoonException.VisitorCodeEmpty | The Besucher code is leer. |
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 ist deaktiviert for the aktuell environment. |
KameleoonException.JSONParse | Couldn’t parse JSON Wert. |
KameleoonException.NumberParse | Couldn’t parse Zahl Wert. |
onConfigurationUpdate()
Verwenden Sie onEvent Methode mit EventType.ConfigurationUpdate stattdessen.
The onConfigurationUpdate() Methode fires a Callback on client Konfiguration aktualisieren.
Diese Methode is applicable only for server-sent Events verwendet in Echtzeit 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();
Arguments
| Name | Typ | Beschreibung |
|---|
| Callback (required) | () => void | Callback Funktion mit no Parameter that wird aufgerufen upon Konfiguration aktualisieren. |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Methode was executed vor the kameleoonClient completed its initialize call. |
getFeatureFlags()
🚫 Doesn’t senden Tracking Daten to Kameleoon
The getFeatureFlags() Methode gibt einen Liste of feature flags stored in der Client Konfiguration.
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();
Zurückgeben Wert
| Typ | Beschreibung |
|---|
FeatureFlagType[] | Liste of feature flags. Jedes feature flag item enthält an id and key. |
Exceptions thrown
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Methode was executed vor the kameleoonClient completed its initialize call. |