Mit dem Kameleoon React SDK können Sie Feature-Experiments ausführen und feature flags in Ihrer Frontend-Web- und Mobilanwendung aktivieren. Die Integration unseres SDK in Ihre Web- und Mobilanwendung ist einfach, und der Footprint (Speicher- und Netzwerknutzung) ist gering.
Erste Schritte: Hilfe für den Einstieg finden Sie im Entwicklerhandbuch
Changelog: Details zur neuesten Version des React SDK finden Sie im Changelog.
SDK-Methoden: Die vollständige Referenzdokumentation des React SDK finden Sie im Abschnitt Referenz.
Anforderungen: Das React SDK erfordert React 16.8.0+
Entwicklerhandbuch
Folgen Sie diesem Abschnitt, um das SDK in Ihre Anwendung zu integrieren und mehr über die Verwendung des SDK zu erfahren.
Erste Schritte
Dieser Abschnitt führt Sie durch die erstmalige Installation und Konfiguration des SDK.
Installation
Das Kameleoon SDK-Installationstool ist der bevorzugte Weg, das SDK zu installieren. Dieser SDK Installer hilft Ihnen, das gewünschte SDK zu installieren, ein einfaches Codebeispiel zu generieren und bei Bedarf external dependencies zu konfigurieren.
Um das SDK-Installationstool zu starten, 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
Erstellen des Kameleoon Clients
Um zu beginnen, erstellen Sie einen Einstiegspunkt für das React SDK, indem Sie den Kameleoon Client auf der obersten Ebene Ihrer Anwendung erstellen. Erstellen Sie eine Instanz von KameleoonClient using the createClient() Funktion, imported vom kameleoon package.
import {
createClient,
Environment,
SDKConfigurationType,
} from '@kameleoon/react-sdk';
// -- Optional configuration
const configuration: Partial<SDKConfigurationType> = {
updateInterval: 60,
environment: Environment.Production,
cookieDomain: '.example.com',
};
const client = createClient({ siteCode: 'my_site_code', configuration });
import { createClient, Environment } from '@kameleoon/react-sdk';
// -- Optional configuration
const configuration = {
updateInterval: 60,
environment: Environment.Production,
cookieDomain: '.example.com',
};
const client = createClient({ siteCode: 'my_site_code', configuration });
Umschließen der Anwendung mit dem Kameleoon Provider
Im zweiten Schritt verbinden Sie den zuvor erstellten Kameleoon Client mit KameleoonProvider indem Sie den konfigurierten Client an KameleoonProvider übergeben:
import {
createClient,
Environment,
KameleoonProvider,
} from '@kameleoon/react-sdk';
const client = createClient({
siteCode: 'my_site_code',
configuration: {
updateInterval: 60,
environment: Environment.Production,
},
});
function AppWrapper(): JSX.Element {
return (
<KameleoonProvider client={client}>
<App />
</KameleoonProvider>
);
}
import {
createClient,
Environment,
KameleoonProvider,
} from '@kameleoon/react-sdk';
const client = createClient({
siteCode: 'my_site_code',
configuration: {
updateInterval: 60,
environment: Environment.Production,
},
});
function AppWrapper() {
return (
<KameleoonProvider client={client}>
<App />
</KameleoonProvider>
);
}
Wenn Sie Next.js für Server-Side Rendering (SSR) verwenden, müssen Sie KameleoonProviderSSR oder KameleoonProvider mit stubMode=true.
Dies verhindert, dass der SDK-Client auf dem Server initialisiert wird, und stellt sicher, dass das React SDK ausschließlich auf der Client-Seite läuft.
import {
createClient,
Environment,
KameleoonProviderSSR,
} from '@kameleoon/react-sdk';
function AppWrapper(): JSX.Element {
return (
<KameleoonProviderSSR sdkParameters={{
siteCode: 'my_site_code',
configuration: {
updateInterval: 60,
environment: Environment.Production,
}
}}>
<App />
</KameleoonProviderSSR>
);
}
Wenn Sie Next.js für Server-Side Rendering (SSR) verwenden, müssen Sie KameleoonProviderSSR oder KameleoonProvider mit stubMode=true.
Dies verhindert, dass der SDK-Client auf dem Server initialisiert wird, und stellt sicher, dass das React SDK ausschließlich auf der Client-Seite läuft.
import {
createClient,
Environment,
KameleoonProviderSSR,
} from '@kameleoon/react-sdk';
function AppWrapper() {
return (
<KameleoonProviderSSR sdkParameters={{
siteCode: 'my_site_code',
configuration: {
updateInterval: 60,
environment: Environment.Production,
}
}}>
<App />
</KameleoonProviderSSR>
);
}
Wenn Sie Next.js für Server-Side Rendering (SSR) verwenden, müssen Sie KameleoonProviderSSR oder KameleoonProvider mit stubMode=true.
Dies verhindert, dass der SDK-Client auf dem Server initialisiert wird, und stellt sicher, dass das React SDK ausschließlich auf der Client-Seite läuft.
import {
createClient,
Environment,
KameleoonProvider,
} from '@kameleoon/react-sdk';
// Checks if the code is running on the server (Node.js) and not in the browser.
// This can be replaced with any other mechanism you use to detect server-side execution.
const isServer = typeof window === 'undefined';
const client = createClient({
siteCode: 'my_site_code',
configuration: {
updateInterval: 60,
environment: Environment.Production,
},
externals: {
// Add your external dependencies here, e.g. storage, eventSource, visitorCodeManager, etc.
},
stubMode: isServer,
});
function AppWrapper(): JSX.Element {
return (
<KameleoonProvider client={client}>
<App />
</KameleoonProvider>
);
}
Wenn Sie Next.js für Server-Side Rendering (SSR) verwenden, müssen Sie KameleoonProviderSSR oder KameleoonProvider mit stubMode=true.
Dies verhindert, dass der SDK-Client auf dem Server initialisiert wird, und stellt sicher, dass das React SDK ausschließlich auf der Client-Seite läuft.
import {
createClient,
Environment,
KameleoonProvider,
} from '@kameleoon/react-sdk';
// Checks if the code is running on the server (Node.js) and not in the browser.
// This can be replaced with any other mechanism you use to detect server-side execution.
const isServer = typeof window === 'undefined';
const client = createClient({
siteCode: 'my_site_code',
configuration: {
updateInterval: 60,
environment: Environment.Production,
},
externals: {
// Add your external dependencies here, e.g. storage, eventSource, visitorCodeManager, etc.
},
stubMode: isServer,
});
function AppWrapper() {
return (
<KameleoonProvider client={client}>
<App />
</KameleoonProvider>
);
}
KameleoonProvider
Verwenden Sie diesen Provider auf der obersten Ebene, indem Sie Ihre App umschließen, um Zugriff zu erhalten auf KameleoonClient. Dies stellt sicher, dass Ihre App beim Start nicht aufgrund von Flag-Änderungen flackert.
Props
| Name | Typ | Beschreibung |
|---|
| children (required) | ReactNode | Untergeordnete Elemente des Providers |
| client (required) | KameleoonClient | KameleoonClient Instanz, erstellt von createClient() |
KameleoonProviderSSR
Verwenden Sie diesen Provider auf der obersten Ebene, indem Sie Ihre App umschließen, um Zugriff zu erhalten auf KameleoonClient.
KameleoonProviderSSR unterscheidet sich von KameleoonProvider dadurch, dass es eine KameleoonClient -Instanz im Kontext bei der ersten Client-Anfrage erstellt. Dies verhindert das Risiko, den Client auf der Serverseite zu erstellen. Es wird zur Verwendung in SSR-basierten Systemen empfohlen, z. B. Next.js mit SSR.
Props
| Name | Typ | Beschreibung |
|---|
| children (required) | ReactNode | Untergeordnete Elemente des Providers |
| sdkParameters (required) | SDKParameters | SDKParameters -Einstellungen zum Erstellen einer Instanz von KameleoonClient |
Warten auf die Client-Initialisierung
KameleoonClient -Initialisierung erfolgt asynchron, um sicherzustellen, dass der Kameleoon-API-Aufruf für diesen Hook erfolgreich war. useInitialize wird verwendet. Sie können async/await, Promise.then() oder eine andere Methode verwenden, um die asynchrone Client-Initialisierung zu behandeln.
import { useEffect, useCallback } from 'react';
import { useInitialize } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
// -- Waiting for the client initialization using `async/await`
const init = useCallback(async (): Promise<void> => {
await initialize();
}, [initialize]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
// -- Waiting for the client initialization using `async/await`
const init = useCallback(async () => {
await initialize();
}, [initialize]);
useEffect(() => {
init();
}, [init]);
}
Aktivieren eines feature flags
Zuweisen einer eindeutigen ID an einen Benutzer
Um einem Benutzer eine eindeutige ID zuzuweisen, können Sie die Methode getVisitorCode() verwenden. Wenn ein visitor code nicht existiert (aus dem Cookie der Request-Header), generiert die Methode eine zufällige eindeutige ID oder verwendet einen defaultVisitorCode , den Sie generiert hätten. Die ID wird dann in einem Response-Headers-Cookie gesetzt.
Wenn Sie Kameleoon im Hybrid mode verwenden, stellt der Aufruf der Methode getVisitorCode() sicher, dass die eindeutige ID (visitor code) zwischen der Anwendungsdatei engine.js (früher kameleoon.js genannt) und dem SDK geteilt wird.
Abrufen einer Flag-Konfiguration
Um einen feature flag in Ihrem Code zu implementieren, müssen Sie zunächst den feature flag in Ihrem Kameleoon-Konto erstellen.
Um den Status oder die Variation eines feature flags für einen bestimmten Benutzer zu bestimmen, sollten Sie die Methode getVariation() oder isFeatureFlagActive() verwenden, um die Konfiguration basierend auf dem featureKey abzurufen.
Die Methode getVariation() behandelt sowohl einfache feature flags mit ON/OFF-Zuständen als auch komplexere Flags mit mehreren Variationen. Die Methode ruft die passende Variation für den Benutzer ab, indem sie die Feature-Regeln prüft, die Variation zuweist und sie basierend auf dem featureKey und visitorCode zurückgibt.
Die Methode isFeatureFlagActive() kann verwendet werden, wenn Sie die Konfiguration eines einfachen feature flags mit nur einem ON- oder OFF-Zustand abrufen möchten, im Gegensatz zu komplexeren feature flags mit mehreren Variationen oder Targeting-Optionen.
Wenn Ihr feature flag zugehörige Variablen hat (wie spezifische Verhaltensweisen, die an jede Variation gebunden sind), getVariation() ermöglicht Ihnen auch den Zugriff auf das Objekt Variation, das Details zur zugewiesenen Variation und zum zugehörigen Experiment liefert. Diese Methode prüft, ob der Benutzer getargetet ist, ermittelt die dem Besucher zugewiesene Variation und speichert sie. Wenn track=true, sendet das SDK das Expositionsereignis bei der nächsten Tracking-Anfrage an das angegebene Experiment, das automatisch basierend auf dem tracking_interval_millisecond des SDK ausgelöst wird. Standardmäßig ist dieses Intervall auf 1000 Millisekunden (1 Sekunde) eingestellt.
Die Methode getVariation() ermöglicht Ihnen zu steuern, ob Tracking durchgeführt wird. Wenn track=false, werden vom SDK keine Expositionsereignisse gesendet. Dies ist nützlich, wenn Sie es vorziehen, keine Daten über das SDK zu tracken und stattdessen auf clientseitiges Tracking durch die Kameleoon-Engine zurückzugreifen. Zusätzlich ist die Einstellung track=false hilfreich bei Verwendung der Methode getVariations() , bei der Sie möglicherweise nur die Variationen für alle Flags benötigen, ohne Tracking-Ereignisse auszulösen. Wenn Sie mehr darüber erfahren möchten, wie Tracking funktioniert, lesen Sie diesen Artikel
Hinzufügen von Datenpunkten, um einen Benutzer zu targeten oder Besuche in Reports zu filtern/aufzuschlüsseln
Um einen Benutzer zu targeten, stellen Sie sicher, dass Sie relevante Datenpunkte zu seinem Profil hinzugefügt haben, bevor Sie die Feature-Variation abrufen oder prüfen, ob der Flag aktiv ist. Verwenden Sie die Methode addData(), um diese Datenpunkte zum Benutzerprofil hinzuzufügen.
Um Datenpunkte abzurufen, die auf anderen Geräten gesammelt wurden, oder um auf frühere Benutzerdaten zuzugreifen (clientseitig erfasst bei der Verwendung von Kameleoon im Hybrid mode), verwenden Sie die Methode getRemoteVisitorData(). Diese Methode ruft Daten asynchron von den Servern ab. Es ist wichtig, getRemoteVisitorData() vor dem Abrufen der Variation oder dem Prüfen, ob der feature flag aktiv ist, aufzurufen, da diese Daten möglicherweise erforderlich sind, um einem Benutzer eine bestimmte Variation zuzuweisen.
Weitere Informationen zu verfügbaren Targeting-Bedingungen finden Sie im ausführlichen Artikel zum Thema.
Zusätzlich stehen die zum Besucherprofil hinzugefügten Datenpunkte zur Verfügung, wenn Sie Ihre Experiments analysieren, sodass Sie Ihre Ergebnisse nach Faktoren wie Gerät und Browser filtern und aufschlüsseln können. Der Kameleoon Hybrid mode sammelt automatisch eine Vielzahl von Datenpunkten auf der Client-Seite, was es einfach macht, Ihre Ergebnisse auf Basis dieser vorab gesammelten Datenpunkte aufzuschlüsseln. Die vollständige Liste finden Sie hier.
Wenn Sie zusätzliche Datenpunkte über das automatisch gesammelte hinaus tracken müssen, können Sie das Custom Data-Feature von Kameleoon verwenden. Mit Custom Data können Sie spezifische Informationen erfassen und analysieren, die für Ihre Experiments relevant sind. Vergessen Sie nicht, die Methode flush() aufzurufen, um die gesammelten Daten zur Analyse an die Kameleoon-Server zu senden.
Um sicherzustellen, dass Ihre Ergebnisse korrekt sind, wird empfohlen, Bots mithilfe des Datentyps UserAgent herauszufiltern.
Tracking von Ziel-Konversionen
Wenn ein Benutzer eine gewünschte Aktion ausführt (z. B. einen Kauf tätigt), wird dies als Konversion aufgezeichnet. Um Konversionen zu tracken, verwenden Sie die Methode trackConversion() und geben Sie die erforderlichen visitorCode und goalId -Parameter an.
Die Konversions-Tracking-Anfrage wird zusammen mit der nächsten geplanten Tracking-Anfrage gesendet, die das SDK in regelmäßigen Abständen sendet (definiert durch tracking_interval_millisecond). Wenn Sie die Anfrage sofort senden möchten, verwenden Sie die Methode flush() mit dem Parameter instant=true.
Senden von Events an Analyselösungen
Um Konversionen zu tracken und Expositionsereignisse an Ihre Kundenanalyselösung zu senden, müssen Sie Kameleoon zunächst im Hybrid mode implementieren. Verwenden Sie dann die Methode getEngineTrackingCode().
Die Methode getEngineTrackingCode() ruft den eindeutigen Tracking-Code ab, der erforderlich ist, um Expositionsereignisse an Ihre Analyselösung zu senden. Mit dieser Methode können Sie Ereignisse aufzeichnen und an die gewünschte Analyseplattform senden.
Hinweise zu React Native
React Native auf der Plattform android unterstützt das Feature Real Time Update nicht.
Während das React SDK in React Native- und React-Kontexten auf die gleiche Weise funktioniert, ist zu beachten, dass sich die Setup-Schritte unterscheiden.
Due zum lack of Browser API in React Native, React SDK has to have different extern Abhängigkeit implementations to work correctly.
Dazu stellt Kameleoon mehrere dedizierte npm-Pakete bereit, die Sie manuell installieren und einrichten oder mithilfe des Kameleoon SDK Installation Tool installieren können (empfohlen).
Die Pakete umfassen:
@kameleoon/react-native-storage - erstellt mit der react-native-mmkv -Bibliothek
@kameleoon/react-native-event-source - erstellt mit der react-native-event-source-ts -Bibliothek
@kameleoon/react-native-visitor-code-manager - aufgebaut auf der react-native-mmkv -Bibliothek
@kameleoon/react-native-platform-analyzer - erstellt mit der react-native -Bibliothek
- optional
@kameleoon/react-native-secure-prng - erstellt mit der react-native-get-random-values -Bibliothek
Wenn Sie die aufgeführten Pakete nicht verwenden möchten, können Sie Ihre eigene Implementierung gemäß dem Leitfaden zu external dependencies.
Beispiel für die Einrichtung des React SDK für eine React Native-Anwendung:
import { createClient } from '@kameleoon/react-sdk';
import { KameleoonEventSource } from '@kameleoon/react-native-event-source';
import { KameleoonStorage } from '@kameleoon/react-native-storage';
import { KameleoonVisitorCodeManager } from '@kameleoon/react-native-visitor-code-manager';
import { KameleoonSecurePRNG } from '@kameleoon/react-native-secure-prng';
import { KameleoonPlatformAnalyzer } from '@kameleoon/react-native-platform-analyzer';
// --- Create KameleoonClient ---
const client = createClient({
siteCode: 'my_site_code',
externals: {
storage: new KameleoonStorage(),
eventSource: new KameleoonEventSource(),
visitorCodeManager: new KameleoonVisitorCodeManager(),
platformAnalyzer: new KameleoonPlatformAnalyzer(),
// -- Optional --
prng: new KameleoonSecurePRNG(),
},
});
import { createClient } from '@kameleoon/react-sdk';
import { KameleoonEventSource } from '@kameleoon/react-native-event-source';
import { KameleoonStorage } from '@kameleoon/react-native-storage';
import { KameleoonVisitorCodeManager } from '@kameleoon/react-native-visitor-code-manager';
import { KameleoonSecurePRNG } from '@kameleoon/react-native-secure-prng';
import { KameleoonPlatformAnalyzer } from '@kameleoon/react-native-platform-analyzer';
// --- Create KameleoonClient ---
const client = createClient({
siteCode: 'my_site_code',
externals: {
storage: new KameleoonStorage(),
eventSource: new KameleoonEventSource(),
visitorCodeManager: new KameleoonVisitorCodeManager(),
platformAnalyzer: new KameleoonPlatformAnalyzer(),
// -- Optional --
prng: new KameleoonSecurePRNG(),
},
});
Verwendung eines benutzerdefinierten Bucketing-Schlüssels
Standardmäßig verwendet Kameleoon eine eindeutige, anonyme Besucher-ID (visitorCode), um Benutzer feature flag-Variationen zuzuweisen. Diese ID wird typischerweise auf dem Gerät des Benutzers generiert und gespeichert (in einem Browser-Cookie für Client-Side- und Server-Side-SDKs, in persistentem Speicher für Mobile-SDKs). In bestimmten Szenarien müssen Sie jedoch möglicherweise sicherstellen, dass alle Benutzer derselben Organisation dieselbe Variante eines feature flags sehen.
Mit der Option Custom Bucketing Key können Sie dieses Standardverhalten überschreiben, indem Sie Ihren eigenen benutzerdefinierten Identifikator für das Bucketing bereitstellen. Diese Überschreibung stellt sicher, dass die Zuweisungslogik von Kameleoon Ihren angegebenen Schlüssel anstelle des Standard-visitorCode.
Anwendungsfälle
Die Verwendung eines benutzerdefinierten Bucketing-Schlüssels ist entscheidend, um Konsistenz und Genauigkeit bei Ihren feature flag-Zuweisungen zu wahren, insbesondere in folgenden Situationen:
- Experiments auf Konto- oder Organisationsebene: Für B2B-Produkte oder Szenarien, in denen Sie alle Benutzer derselben Organisation derselben Variation zuweisen möchten, können Sie einen Identifikator wie eine
accountId verwenden. Benutzerdefinierte Bucketing-Schlüssel sind entscheidend für A/B-Tests von Features, die ein gesamtes Team oder Unternehmen betreffen.
Durch die Implementierung eines benutzerdefinierten Bucketing-Schlüssels gewährleisten Sie eine höhere Konsistenz und Genauigkeit in Ihren Experiments, was zu zuverlässigeren Ergebnissen und einer besseren Benutzererfahrung führt.
Technische Details
Wenn Sie einen benutzerdefinierten Bucketing-Schlüssel für einen feature flag konfigurieren, stellen Sie Kameleoon einen bestimmten Identifikator aus den Daten Ihrer Anwendung bereit:
addData(visitorCode, new CustomData(index, 'newVisitorCode'));
- Bereitstellen des benutzerdefinierten Schlüssels: Sie stellen dem Kameleoon SDK Ihren benutzerdefinierten Identifikator mithilfe der Methode
addData() bereit. In dieser Methode übergeben Sie Ihren gewählten benutzerdefinierten Bucketing-Schlüssel als CustomData -Objekt. Hier bezieht sich newVisitorCode auf den Identifikator, den Sie für Ihr Bucketing verwenden möchten (z. B. die neue userId oder accountId).
Damit der benutzerdefinierte Bucketing-Schlüssel korrekt funktioniert, muss er auch für den feature flag während der Flag-Erstellung oder -Bearbeitung definiert und konfiguriert werden. Ohne diese entsprechende Konfiguration wendet das Bucketing des SDK Ihren benutzerdefinierten Schlüssel nicht an. Detaillierte Anweisungen zur Einrichtung in Kameleoon finden Sie in diesem Artikel.
- Bucketing-Logik: Sobald ein benutzerdefinierter Bucketing-Schlüssel über die Methode
addData() bereitgestellt wird, verwenden alle Hash-Berechnungen für die Zuweisung von Benutzern zu Variationen diesen newVisitorCode (Ihren benutzerdefinierten Schlüssel) anstelle des Standard-visitorCode. Die Verwendung des newVisitorCode bedeutet, dass die Bucketing-Entscheidung an Ihren benutzerdefinierten Identifikator gebunden ist, was konsistente Zuweisungen in verschiedenen Kontexten gewährleistet, in denen dieser Identifikator vorhanden ist.
- Datentracking und Analyse: Es ist wichtig zu beachten, dass der
newVisitorCode (Ihr benutzerdefinierter Schlüssel) für Bucketing-Entscheidungen verwendet wird, alle nachfolgenden Daten (z. B. Tracking-Ereignisse und Konversionen) jedoch gesendet und mit dem ursprünglichen visitorCode verknüpft sind. Diese Trennung stellt sicher, dass Ihre Analysen die individuellen Benutzerwege und Interaktionen im breiteren Kontext Ihres Experiments korrekt widerspiegeln, auch wenn das Bucketing auf einer höheren Ebene (wie einem Konto) oder über mehrere Geräte/Sitzungen hinweg erfolgt. Ihre ursprünglichen Besucherdaten bleiben für umfassende Berichte intakt.
Technische Anforderungen
Um einen benutzerdefinierten Bucketing-Schlüssel effektiv zu nutzen:
- Der Schlüssel muss ein
string sein.
- Er muss für die Entität, die Sie bucketieren möchten, eindeutig sein (z. B. wenn Sie eine
userId verwenden, sollte die ID jedes Benutzers eindeutig sein).
- Der Schlüssel muss dem SDK genau in dem Moment zur Verfügung stehen, in dem die feature flag-Entscheidung für diesen Benutzer oder diese Anfrage ausgewertet wird.
Targeting-Bedingungen
Die Kameleoon SDKs unterstützen eine Vielzahl vordefinierter Targeting-Bedingungen, mit denen Sie Benutzer in Ihren Kampagnen targeten können.
Eine Liste der von diesem SDK unterstützten Bedingungen finden Sie unter use visit history to target users.
Sie können auch Ihre eigenen external data to target users.
Logging
Das SDK generiert Logs, die verschiedene interne Prozesse und Probleme widerspiegeln.
Log-Level
Das SDK unterstützt die Begrenzung des Loggings nach Log-Level.
import { KameleoonClient, KameleoonLogger, LogLevel } from '@kameleoon/react-sdk';
const client = createClient({ 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 main behaviour.
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/react-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/react-sdk’;
const client = createClient({ siteCode: ‘my_site_code’, configuration });
// The `NONE` log level allows no 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 main behaviour.
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/react-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);
Benutzerdefinierte Log-Behandlung
Das SDK schreibt seine Logs standardmäßig in die Konsolenausgabe. Dieses Verhalten kann überschrieben werden.
Die Log-Begrenzung nach Log-Level erfolgt unabhängig von der Log-Behandlungslogik.
import { KameleoonClient, KameleoonLogger, IExternalLogger, LogLevel } from '@kameleoon/react-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 = createClient({
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/react-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 = createClient({
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-Informationen
Sie geben eine Domain als domain in KameleoonClient [Konfiguration] an, die zum Speichern des Kameleoon-Besucher-Codes in Cookies verwendet wird. Dies ist wichtig bei der Arbeit mit den Methoden getVisitorCode und setLegalConsent Die von Ihnen angegebene Domain wird im Cookie als Domain=-Schlüssel gespeichert.
Festlegen der Domain
Die von Ihnen angegebene Domain gibt an, dass die URL-Adresse das Cookie verwenden kann. Wenn Ihre Domain z. B. www.example.com. ist, ist das Cookie nur von einer www.example.com-URL aus verfügbar. Das bedeutet, dass Seiten mit der Domain app.example.com das Cookie nicht verwenden können.
Um flexibler mit Subdomains umzugehen, können Sie einer Domain ein . voranstellen. Beispielsweise erlaubt die Domain .example.com, dass das Cookie sowohl auf app.example.com als auch auf login.example.com funktioniert.
Sie können keine regulären Ausdrücke, Sonderzeichen, Protokolle oder Portnummern im domain verwenden.
Außerdem darf eine bestimmte Liste von Subdomains nicht mit dem Präfix . verwendet werden.
Hier ist ein kleiner Domain-Spickzettel:
| Domain | Zulässige URLs | Unzulässige 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 | ⛔ ungültige Domain | ⛔ ungültige Domain |
www.example.com:4408 | ⛔ ungültige Domain | ⛔ ungültige Domain |
.localhost.com = localhost | ⛔ ungültige Domain | ⛔ ungültige Domain |
Entwicklung auf localhost
localhost wird immer als ungültige Domain betrachtet, was das Testen der Domain bei der Entwicklung auf localhost erschwert.
Es gibt zwei Möglichkeiten, dieses Problem zu vermeiden:
- Geben Sie das Feld
domain im SDK-Client beim Testen nicht an. Dies verhindert localhost -Probleme (das Cookie wird auf jeder Domain gesetzt).
- Erstellen Sie eine lokale Domain für
localhost. Zum Beispiel:
- Navigieren Sie zu
/etc/hosts unter Linux oder zu c:\Windows\System32\Drivers\etc\hosts unter Windows
- Öffnen Sie
hosts mit Superuser- oder Administratorrechten
- Fügen Sie dem localhost-Port eine Domain hinzu, z. B.:
127.0.0.1 app.com
- Jetzt können Sie Ihre App lokal auf
app.com:{my_port} ausführen und .app.com als Ihre Domain angeben
External dependencies
Externe SDK-Abhängigkeiten verwenden das Muster dependency injection, um Ihnen die Möglichkeit zu geben, Ihre eigenen Implementierungen für bestimmte Teile eines SDK bereitzustellen.
Im React SDK haben alle external dependencies Standardimplementierungen, die eine native Browser-API verwenden, sodass keine Bereitstellung erforderlich ist, es sei denn, eine andere API ist für bestimmte Anwendungsfälle erforderlich.
Hier ist die Liste der verfügbaren external dependencies:
| Abhängigkeit | Schnittstelle | Verwendete API | Beschreibung |
|---|
storage (optional) | IExternalStorage | Browser localStorage | Wird verwendet, um alle vorhandenen und gesammelten SDK-Daten zu speichern |
requester (optional) | IExternalRequester | Browser fetch | Wird verwendet, um alle Netzwerkanfragen auszuführen |
eventSource (optional) | IExternalEventSource | Browser EventSource | Wird verwendet, um Server-Sent-Events für Real Time Update -Funktionen zu empfangen |
visitorCodeManager (optional) | IExternalVisitorCodeManager | Browser Cookie | Wird verwendet, um den visitor code zu speichern und zu synchronisieren |
prng (optional) | IExternalPRNG | Math.random or Browser crypto.getRandomValues | Wird verwendet, um eindeutige IDs für Tracking-Ereignisse zu generieren |
logger (optional) | ILogger | Custom implementation | Wird für die benutzerdefinierte Behandlung von Logs aus dem SDK verwendet. Ermöglicht zu definieren, wie Logs verarbeitet und wohin sie ausgegeben werden. |
platformAnalyzer (optional) | IPlatformAnalyzer | React Native API | Erkennt die Plattform automatisch und fügt diese Informationen den Besucherdaten hinzu. Speziell für React Native entwickelt. |
Das folgende Beispiel implementiert external dependencies. Um eine Schnittstelle aus einem SDK zu importieren, erstellen Sie eine Klasse, die sie implementiert, und übergeben Sie die instanziierte Klasse an das SDK.
Storage
import { IExternalStorage } from '@kameleoon/react-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 = createClient({
siteCode: 'my_site_code',
externals: {
storage: new MyStorage(),
},
});
import { KameleoonClient } from '@kameleoon/react-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 = createClient({
siteCode: 'my_site_code',
externals: {
storage: new MyStorage(),
},
});
EventSource
import {
IExternalEventSource,
EventSourceOpenParametersType,
} from '@kameleoon/react-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 = createClient({
siteCode: 'my_site_code',
externals: {
eventSource: new MyEventSource(),
},
});
// --- 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 = createClient({
siteCode: 'my_site_code',
externals: {
eventSource: new MyEventSource(),
},
});
VisitorCodeManager
import {
IExternalVisitorCodeManager,
SetDataParametersType,
KameleoonUtils,
} from '@kameleoon/react-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 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 = createClient({
siteCode: 'my_site_code',
externals: {
visitorCodeManager: new MyVisitorCodeManager(),
},
});
import { KameleoonUtils } from '@kameleoon/react-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 = createClient({
siteCode: 'my_site_code',
externals: {
visitorCodeManager: new MyVisitorCodeManager(),
},
});
Requester
import {
RequestType,
IExternalRequester,
KameleoonResponseType,
SendRequestParametersType,
} from '@kameleoon/react-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 = createClient({
siteCode: 'my_site_code',
externals: {
requester: new MyRequester(),
},
});
import { KameleoonClient } from '@kameleoon/react-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(),
},
});
Pseudo Random Number Generator
Pseudo Random Number Generator (PRNG) ist eine Abhängigkeit, die eine zufällige Gleitkommazahl zwischen 0 und 1 erzeugt (ähnlich zu Math.random).
Die standardmäßige Kameleoon-Implementierung basiert auf der Browser-Funktion crypto oder Math.random , falls crypto nicht verfügbar ist.
Diese APIs sind sehr sicher und zuverlässig, jedoch möchten Sie in einigen Randfällen (insbesondere in einigen React Native -Engines) möglicherweise Ihre eigene Implementierung bereitstellen oder ein dediziertes Kameleoon-Paket für React Native verwenden - @kameleoon/react-native-secure-prng
import { IExternalPRNG } from '@kameleoon/react-sdk';
// --- External Pseudo Random Number Generator (PRNG) implementation ---
class MyPRNG implements IExternalPRNG {
public getRandomNumber(): number {
// Return a random floating point number between `0` und `1`, like `Math.random()` does.
return Math.random();
}
}
// --- Create KameleoonClient ---
const client = createClient({
siteCode: 'my_site_code',
externals: {
prng: new MyPRNG(),
},
});
// --- External Pseudo Random Number Generator (PRNG) implementation ---
class MyPRNG {
getRandomNumber() {
// Return a random floating point number between `0` und `1`, like `Math.random()` does.
return Math.random();
}
}
// --- Create KameleoonClient ---
const client = createClient({
siteCode: 'my_site_code',
externals: {
prng: new MyPRNG(),
},
});
Fehlerbehandlung
Fast jeder React SDK-Callback, der von Hooks zurückgegeben wird, kann irgendwann einen Fehler werfen. Diese Fehler sind nicht nur Warnhinweise, sondern bewusst vordefinierte KameleoonErrors
die die nativ JavaScript-Klasse Error erweitern und nützliche Meldungen sowie ein spezielles Feld type vom Typ KameleoonException.
KameleoonException ist ein Enum, das alle möglichen Fehlertypen enthält.
Um genau zu wissen, welche Art von KameleoonException die Callbacks werfen können, können Sie den Abschnitt Throws der Hook-Beschreibung auf dieser Seite überprüfen oder einfach den Mauszeiger über den Callback in Ihrer IDE bewegen, um die jsdocs-Beschreibung anzuzeigen.
Insgesamt gilt die Fehlerbehandlung als gute Praxis, um Ihre Anwendung stabiler zu machen und technische Probleme zu vermeiden.
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useVisitorCode,
useData,
CustomData,
KameleoonError,
KameleoonException,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { addData } = useData();
const init = useCallback(async (): Promise<void> => {
try {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
const customData = new CustomData(0, 'my_data');
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;
}
}
}
}, [initialize, addData, visitorCode, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useVisitorCode,
useData,
CustomData,
KameleoonException,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { addData } = useData();
const init = useCallback(async () => {
try {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
const customData = new CustomData(0, 'my_data');
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;
}
}
}, [initialize, addData, visitorCode, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
Cross-Device-Experimentation
Um Besucher zu unterstützen, die von mehreren Geräten aus auf eine App zugreifen, ermöglicht Kameleoon die Synchronisierung zuvor gesammelter Besucherdaten über jedes Gerät des Besuchers hinweg und die Abgleichung des Besuchsverlaufs über Geräte hinweg durch Cross-Device-Experimentation. Fallstudien und detaillierte Informationen darüber, wie Kameleoon Daten geräteübergreifend verarbeitet, finden Sie im Artikel zur Cross-Device-Experimentation.
Synchronisierung von Custom Data über Geräte hinweg
Obwohl die benutzerdefinierte Mapping-Synchronisierung verwendet wird, um Besucherdaten geräteübergreifend abzugleichen, ist sie nicht immer erforderlich. Im Folgenden sind zwei Szenarien aufgeführt, in denen keine benutzerdefinierte Mapping-Synchronisierung erforderlich ist:
Dieselbe Benutzer-ID auf allen Geräten
Wenn dieselbe Benutzer-ID konsistent auf allen Geräten verwendet wird, erfolgt die Synchronisierung automatisch ohne benutzerdefinierte Mapping-Synchronisierung. Es genügt, die Methode getRemoteVisitorData() aufzurufen, wenn Sie die zwischen mehreren Geräten gesammelten Daten synchronisieren möchten.
Multi-Server-Instanzen mit konsistenten IDs
In komplexen Setups mit mehreren Servern (z. B. verteilten Serverinstanzen), bei denen dieselbe Benutzer-ID auf allen Servern verfügbar ist, ist die Synchronisierung zwischen Servern (mit getRemoteVisitorData()) ohne zusätzliche benutzerdefinierte Mapping-Synchronisierung ausreichend.
Kunden, die zusätzliche Daten benötigen, können die Beschreibung der Methode getRemoteVisitorData() für weitere Anleitungen heranziehen. Im folgenden Code wird angenommen, dass derselbe eindeutige Identifikator (in diesem Fall der visitorCode, der auch als userId) bezeichnet werden kann) konsistent zwischen den beiden Geräten verwendet wird, um Daten korrekt abzurufen.
Wenn Sie die gesammelten Daten in Echtzeit synchronisieren möchten, müssen Sie den Scope Visitor für Ihre Custom Data wählen.
import { useEffect, useCallback } from 'react';
import { useInitialize, useData, CustomData } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { addData, flush } = useData();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Custom Data with index `0` was set to `Visitor` scope
// in Kameleoon.
const customDataIndex = 0;
const customData = new CustomData(customDataIndex, 'my_data');
addData('my_visitor', customData);
flush();
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize, useData, CustomData } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getRemoteVisitorData } = useData();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Before working with data, call `getRemoteVisitorData`.
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 to target and track "my_visitor".
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize, useData, CustomData } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { addData, flush } = useData();
const init = useCallback(async () => {
await initialize();
// -- Custom Data with index `0` was set to `Visitor` scope
// in Kameleoon.
const customDataIndex = 0;
const customData = new CustomData(customDataIndex, 'my_data');
addData('my_visitor', customData);
flush();
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize, useData, CustomData } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getRemoteVisitorData } = useData();
const init = useCallback(async () => {
await initialize();
// -- Before working with data, call `getRemoteVisitorData`.
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 to target and track "my_visitor".
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
Verwendung von Custom Data für Session-Zusammenführung
SDK Version 9
SDK Version 10
Cross-Gerät experimentation allows you to combine a Besucher’s Verlauf across each derir Geräte (Verlauf Abgleich). One der powerful features that Verlauf Abgleich bietet is the ability to merge different Besucher Sitzungen into one. To reconcile visit Verlauf, you can use CustomData verwenden, um einen eindeutigen Identifikator für den Besucher bereitzustellen.Follow the activating cross-Gerät Verlauf Abgleich guide to set up your Custom Data on the Kameleoon PlattformWenn Ihre Custom Data eingerichtet sind, können Sie sie in Ihrem Code verwenden, um die Sitzung eines Besuchers zusammenzuführen.
Sitzungen mit demselben Identifikator sehen immer dieselbe Experiment-Variation und werden als ein einzelner Besucher in der Ansicht Visitor auf den Ergebnisseiten Ihres Experiments angezeigt.Die SDK-Konfiguration stellt sicher, dass zugeordnete Sitzungen immer dieselbe Variation des Experiments sehen.Anschließend können Sie das SDK normal verwenden. Die folgenden Methoden können im Kontext der Session-Zusammenführung hilfreich sein:
- Use
getRemoteVisitorData with isUniqueIdentifier=true , um Daten für alle verknüpften Besucher abzurufen
- Use
trackConversion oder flush with isUniqueIdentifier=true , um bestimmte Daten für einen bestimmten Besucher zu tracken, der einem anderen Besucher zugeordnet ist
Hier ist ein Beispiel, wie Sie Custom Data für die Session-Zusammenführung verwenden. In diesem Beispiel haben wir eine Anwendung mit einer Login-Seite. Da wir die Benutzer-ID zum Zeitpunkt des Logins nicht kennen, verwenden wir einen anonymen Besucher-Identifikator, der durch die Methode getVisitorCode generiert wird. Nachdem sich der Benutzer angemeldet hat, können wir den anonymen Besucher mit der Benutzer-ID verknüpfen und sie als eindeutigen Identifikator für den Besucher verwenden.import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
CustomData,
} from '@kameleoon/react-sdk';
function LoginPage(): JSX.Element {
const [visitorCode, setVisitorCode] = useState<string | null>(null);
const { initialize } = useInitialize();
const { getVariation } = useFeatureFlag();
const { getVisitorCode } = useVisitorCode();
const init = useCallback(async (): Promise<void> => {
await initialize();
const anonymousVisitor = getVisitorCode();
// -- Saving `visitorCode` in the state to re-use it later.
setVisitorCode(anonymousVisitor);
// -- Getting a variation, assume it's variation `A`
const variation = getVariation({
visitorCode: anonymousVisitor,
featureKey: 'my_feature_key',
});
}, [initialize, getVariation, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useData,
useFeatureFlag,
useVisitorCode,
CustomData,
} from '@kameleoon/react-sdk';
type Props = {
anonymousVisitor: string;
};
function ApplicationPage(props: Props): JSX.Element {
const { addData, trackConversion, getRemoteVisitorData } = useData();
const { getVariation } = useFeatureFlag();
const init = useCallback(async (): 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');
// -- Let's assume the anonymous visitor identifier
// was passed as a prop.
addData(props.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 = getVariation({
visitorCode: 'my_user_id',
featureKey: 'my_feature_key',
});
// -- `my_user_id` und `anonymousVisitor` are now linked.
// They can be tracked as a single visitor.
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 getRemoteVisitorData({
visitorCode: 'my_user_id',
// -- Informing the SDK that the visitor is a unique identifier.
isUniqueIdentifier: true,
});
}, [
getRemoteVisitorData,
trackConversion,
addData,
getVariation,
]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
CustomData,
} from '@kameleoon/react-sdk';
function LoginPage() {
const [visitorCode, setVisitorCode] = useState(null);
const { initialize } = useInitialize();
const { getVariation } = useFeatureFlag();
const { getVisitorCode } = useVisitorCode();
const init = useCallback(async () => {
await initialize();
const anonymousVisitor = getVisitorCode();
// -- Saving `visitorCode` in the state to re-use it later.
setVisitorCode(anonymousVisitor);
// -- Getting a variation, assume it's variation `A`
const variation = getVariation({
visitorCode: anonymousVisitor,
featureKey: 'my_feature_key',
});
}, [initialize, getVariation, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useData,
useFeatureFlag,
useVisitorCode,
CustomData,
} from '@kameleoon/react-sdk';
function ApplicationPage(props) {
const { addData, trackConversion, getRemoteVisitorData } = useData();
const { getVariation } = useFeatureFlag();
const init = useCallback(async () => {
// -- 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');
// -- Let's assume the anonymous visitor identifier
// was passed as a prop.
addData(props.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 = getVariation({
visitorCode: 'my_user_id',
featureKey: 'my_feature_key',
});
// -- `my_user_id` und `anonymousVisitor` are now linked.
// They can be tracked as a single visitor.
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 getRemoteVisitorData({
visitorCode: 'my_user_id',
// -- Informing the SDK know the visitor is a unique identifier.
isUniqueIdentifier: true,
});
}, [
getRemoteVisitorData,
trackConversion,
addData,
getVariation,
]);
useEffect(() => {
init();
}, [init]);
}
Cross-Gerät experimentation allows you to combine a Besucher’s Verlauf across each derir Geräte (Verlauf Abgleich). One der powerful features that Verlauf Abgleich bietet is the ability to merge different Besucher Sitzungen into one. To reconcile visit Verlauf, you can use CustomData verwenden, um einen eindeutigen Identifikator für den Besucher bereitzustellen.Follow the activating cross-Gerät Verlauf Abgleich guide to set up your Custom Data on the Kameleoon PlattformWenn Ihre Custom Data eingerichtet sind, können Sie sie in Ihrem Code verwenden, um die Sitzung eines Besuchers zusammenzuführen.
Sitzungen mit demselben Identifikator sehen immer dieselbe Experiment-Variation und werden als ein einzelner Besucher in der Ansicht Visitor auf den Ergebnisseiten Ihres Experiments angezeigt.Die SDK-Konfiguration stellt sicher, dass zugeordnete Sitzungen immer dieselbe Variation des Experiments sehen.Bevor Sie andere Methoden verwenden, stellen Sie sicher, dass Sie dem SDK mitteilen, dass der Besucher ein eindeutiger Identifikator ist, indem Sie UniqueIdentifier -Daten zu einem Besucher hinzufügenHier ist ein Beispiel, wie Sie Custom Data für die Session-Zusammenführung verwenden. In diesem Beispiel haben wir eine Anwendung mit einer Login-Seite. Da wir die Benutzer-ID zum Zeitpunkt des Logins nicht kennen, verwenden wir einen anonymen Besucher-Identifikator, der durch die Methode getVisitorCode generiert wird. Nachdem sich der Benutzer angemeldet hat, können wir den anonymen Besucher mit der Benutzer-ID verknüpfen und sie als eindeutigen Identifikator für den Besucher verwenden.import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
CustomData,
} from '@kameleoon/react-sdk';
function LoginPage(): JSX.Element {
const [visitorCode, setVisitorCode] = useState<string | null>(null);
const { initialize } = useInitialize();
const { getVariation } = useFeatureFlag();
const { getVisitorCode } = useVisitorCode();
const init = useCallback(async (): Promise<void> => {
await initialize();
const anonymousVisitor = getVisitorCode();
// -- Saving `visitorCode` in the state to re-use it later.
setVisitorCode(anonymousVisitor);
// -- Getting a variation, assume it's variation `A`
const variation = getVariation({
visitorCode: anonymousVisitor,
featureKey: 'my_feature_key',
});
}, [initialize, getVariation, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useData,
useFeatureFlag,
useVisitorCode,
CustomData,
UniqueIdentifier,
} from '@kameleoon/react-sdk';
type Props = {
anonymousVisitor: string;
};
function ApplicationPage(props: Props): JSX.Element {
const { addData, trackConversion, getRemoteVisitorData, flush } = useData();
const { getVariation } = useFeatureFlag();
const init = useCallback(async (): 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');
// -- Let's assume the anonymous visitor identifier
// was passed as a prop.
addData(props.anonymousVisitor, userIdentifierData);
// -- Flushing data for the anonymous `visitorCode`
flush(props.anonymousVisitor);
// -- Informing the SDK that the visitor is unique identifier.
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 = getVariation({
visitorCode: 'my_user_id',
featureKey: 'my_feature_key',
});
// -- `my_user_id` und `anonymousVisitor` are now linked.
// They can be tracked as a single visitor.
trackConversion({
visitorCode: 'my_user_id',
goalId: 123,
revenue: 100,
});
// -- Additionally, linked visitors share previously
// collected remote data.
const data = await getRemoteVisitorData({
visitorCode: 'my_user_id',
});
}, [
getRemoteVisitorData,
trackConversion,
addData,
getVariation,
]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
CustomData,
} from '@kameleoon/react-sdk';
function LoginPage() {
const [visitorCode, setVisitorCode] = useState(null);
const { initialize } = useInitialize();
const { getVariation } = useFeatureFlag();
const { getVisitorCode } = useVisitorCode();
const init = useCallback(async () => {
await initialize();
const anonymousVisitor = getVisitorCode();
// -- Saving `visitorCode` in the state to re-use it later.
setVisitorCode(anonymousVisitor);
// -- Getting a variation, assume it's variation `A`
const variation = getVariation({
visitorCode: anonymousVisitor,
featureKey: 'my_feature_key',
});
}, [initialize, getVariation, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useData,
useFeatureFlag,
useVisitorCode,
CustomData,
UniqueIdentifier,
} from '@kameleoon/react-sdk';
function ApplicationPage(props) {
const { addData, trackConversion, getRemoteVisitorData, flush } = useData();
const { getVariation } = useFeatureFlag();
const init = useCallback(async () => {
// -- 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');
// -- Let's assume the anonymous visitor identifier
// was passed as a prop.
addData(props.anonymousVisitor, userIdentifierData);
// -- Flushing data for the anonymous `visitorCode`
flush(props.anonymousVisitor);
// -- Informing the SDK that the visitor is a unique identifier.
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` und `anonymousVisitor` are now linked.
// They can be tracked as a single visitor.
trackConversion({
visitorCode: 'my_user_id',
goalId: 123,
revenue: 100,
});
// -- Additionally, linked visitors share previously
// collected remote data.
const data = await getRemoteVisitorData({
visitorCode: 'my_user_id',
});
}, [
getRemoteVisitorData,
trackConversion,
addData,
getVariation,
]);
useEffect(() => {
init();
}, [init]);
}
Utilities
Das SDK verfügt über eine Reihe von Utility-Methoden, die zur Vereinfachung des Entwicklungsprozesses verwendet werden können. Alle Methoden werden als statische Mitglieder der Klasse KameleoonUtils class.
simulateSuccessRequest
Die Methode simulateSuccessRequest is wird verwendet, um simulate a erfolgreich Anfrage zum Kameleoon server. It kann nützlich for custom Requester implementations when developer needs to simulate a erfolgreich Anfrage, zum Beispiel disabling tracking.
import {
KameleoonUtils,
IExternalRequester,
SendRequestParametersType,
RequestType,
KameleoonResponseType,
} from '@kameleoon/react-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/react-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);
}
}
Argumente
| Name | Typ | Beschreibung |
|---|
| requestType (required) | RequestType | Ein Anfragetyp |
| data (required) | SimulateRequestDataType[RequestType] | Ein Anfragetyp data, which is different depending on RequestType |
Data type SimulateRequestDataType ist wie folgt definiert:
RequestType.Tracking - null
RequestType.ClientConfiguration - ClientConfigurationDataType
RequestType.RemoteData - JSONType
Rückgabewert
| Typ | Beschreibung |
|---|
Promise<KameleoonResponseType> | gibt ein Promise mit der Antwort der Anfrage zurück |
getCookieValue
Die Methode getCookieValue wird verwendet, um eine gängige Cookie-Zeichenfolge zu parsen (key_1=value_1; key_2=value_2; ...) und den Wert eines bestimmten Cookie-Schlüssels abzurufen. Sie ist nützlich, wenn mit einer benutzerdefinierten Implementierung von VisitorCodeManager.
import { KameleoonUtils } from '@kameleoon/react-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/react-sdk';
const cookies = 'key_1=value_1; key_2=value_2';
const key = 'key_1';
const value = KameleoonUtils.getCookieValue(cookies, key); // = `value_1`
Argumente
| Name | Typ | Beschreibung |
|---|
| Cookie (required) | string | Cookie-Zeichenfolge in der Form key_1=value_1; key_2=value_2 |
| key (required) | string | String-Darstellung eines Schlüssels, nach dem ein Wert gesucht werden soll |
Rückgabewert
| Typ | Beschreibung | |
|---|
| `string | null` | gibt eine Zeichenfolge mit einem Cookie-Wert oder null zurück, wenn der Schlüssel nicht gefunden wurde |
Referenz
Dies ist die vollständige Referenzdokumentation für das React SDK.
Initialisierung
Dieser Abschnitt enthält die Methoden, die Sie zum Erstellen und Initialisieren des Kameleoon Client in Ihrer Anwendung verwenden.
initialisieren()
SDK Version 9
SDK Version 10
An asynchronous initialize Funktion, collected with useInitialize Hook, that’s wird verwendet für KameleoonClient Initialisierung 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 there is an older Konfiguration verfügbar in SDK Speicher, das SDK uses the older Konfiguration as a fallback and the
initialize does not throw an Fehler.
-
Client Initialisierung has an optional offline mode.
Es ist activated by setting optional
useCache Parameter to true.
In offline mode if tracking Anfragen from any der following Methoden fail due to internet connectivity issues, das SDK automatically resends the Anfrage as soon as it detects that the internet connection has been re-established:import { useEffect, useCallback } from 'react';
import { useInitialize } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const init = useCallback(async (): Promise<void> => {
await initialize();
}, [initialize]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const init = useCallback(async () => {
await initialize();
}, [initialize]);
useEffect(() => {
init();
}, [init]);
}
Argumente
| Name | Typ | Beschreibung | Standardwert |
|---|
| useCache (optional) | boolean oder undefined | Parameter for activating SDK offline Modus, if true is passed failed polls will not return Fehler and will use cached data if such data is verfügbar | false |
Rückgabewert
| Typ | Beschreibung |
|---|
Promise<boolean> | a promise resolved to a boolean indicating a erfolgreich sdk Initialisierung. Generally initialisieren will throw an Fehler if the something that can not be handled will happen, so the boolean Wert will almost always be true and won’t give as much nützlich Informationen. |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.StorageWrite | Speicherdaten konnten nicht aktualisiert werden |
KameleoonException.ClientConfiguration | Client-Konfiguration konnte nicht von der Kameleoon-API abgerufen werden |
KameleoonException.MaximumRetriesReached | Maximale Anzahl an Wiederholungen erreicht, Anfrage fehlgeschlagen |
An asynchronous initialize Funktion, collected with useInitialize Hook, that’s wird verwendet für KameleoonClient Initialisierung 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 there is an older Konfiguration verfügbar in SDK Speicher, das SDK uses the older Konfiguration as a fallback and the
initialize does not throw an Fehler.
-
SDK supports an offline mode.
In offline mode if tracking Anfragen from any der following Methoden fail due to internet connectivity issues, das SDK automatically resends the Anfrage as soon as it detects that the internet connection has been re-established:import { useEffect, useCallback } from 'react';
import { useInitialize } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const init = useCallback(async (): Promise<void> => {
await initialize();
}, [initialize]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const init = useCallback(async () => {
await initialize();
}, [initialize]);
useEffect(() => {
init();
}, [init]);
}
Rückgabewert
| Typ | Beschreibung |
|---|
Promise<boolean> | a promise resolved to a boolean indicating a erfolgreich sdk Initialisierung. Generally initialisieren will throw an Fehler if the something that can not be handled will happen, so the boolean Wert will almost always be true and won’t give as much nützlich Informationen. |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.StorageWrite | Speicherdaten konnten nicht aktualisiert werden |
KameleoonException.ClientConfiguration | Client-Konfiguration konnte nicht von der Kameleoon-API abgerufen werden |
KameleoonException.MaximumRetriesReached | Maximale Anzahl an Wiederholungen erreicht, Anfrage fehlgeschlagen |
isInitialized()
The isInitialized Funktion, collected mit dem useInitialize Hook, is a small utility Methode that checks if das SDK Initialisierung has completed. Zum Beispiel, this kann nützlich when dealing with a deeply nested Komponente tree, because it allows you to quickly check das SDK readiness without having to manage a global state, or pass the Initialisierung result using Komponente props.
import { useEffect, useCallback } from 'react';
import { useInitialize, useFeatureFlag } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const init = useCallback(async (): Promise<void> => {
await initialize();
}, [initialize]);
useEffect(() => {
init();
}, [init]);
}
function DeeplyNestedComponent(): JSX.Element {
const { isInitialized } = useInitialize();
const { getVariation } = useFeatureFlag();
if (isInitialized()) {
const variation = getVariation({ visitorCode: 'visitor_code', featureKey: 'my_feature_key' });
}
}
import { useEffect, useCallback } from 'react';
import { useInitialize, useFeatureFlag } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const init = useCallback(async () => {
await initialize();
}, [initialize]);
useEffect(() => {
init();
}, [init]);
}
function DeeplyNestedComponent() {
const { isInitialized } = useInitialize();
const { getVariation } = useFeatureFlag();
if (isInitialize()) {
const variation = getVariation({ visitorCode: 'visitor_code', featureKey: 'my_feature_key' });
}
}
Rückgabewert
A boolean Wert. Returns true if SDK was successfully initialized, otherwise returns false.
createClient()
To get started, you need to create an entry point for React SDK by creating a Kameleoon Client at the top level of your Anwendung using the createClient() Funktion imported from kameleoon package.
An Instanz of KameleoonClient is created using createClient() Funktion.
import {
createClient,
Environment,
SDKConfigurationType,
} from '@kameleoon/react-sdk';
// -- Optional configuration
const configuration: Partial<SDKConfigurationType> = {
updateInterval: 60,
environment: Environment.Production,
cookieDomain: '.example.com',
};
const client = createClient({ siteCode: 'my_site_code', configuration });
import { createClient, Environment } from '@kameleoon/react-sdk';
// -- Optional configuration
const configuration = {
updateInterval: 60,
environment: Environment.Production,
cookieDomain: '.example.com',
};
const client = createClient({ siteCode: 'my_site_code', configuration });
Argumente
An Objekt of type SDKParameters containing:
| Name | Typ | Beschreibung |
|---|
| siteCode (required) | string | Dies ist a eindeutig key der Kameleoon project you are using mit dem SDK. This field is erforderlich. |
| Konfiguration (optional) | Partial<SDKConfigurationType> | client’s Konfiguration |
| externals (optional) | ExternalsType | extern implementation of SDK Abhängigkeiten (External Abhängigkeiten) |
Konfigurationsparameter
SDK Version 9
SDK Version 10
| Name | Typ | Beschreibung | Standardwert |
|---|
| updateInterval (optional) | number | Gibt das Aktualisierungsintervall in Minuten an, in dem das SDK die Konfiguration für die aktiven Experiments und feature flags abruft. Der Wert bestimmt die maximale Zeit, die benötigt wird, um Änderungen wie das Aktivieren oder Deaktivieren von feature flags oder das Starten von Experiments an Ihre Produktionsserver zu übertragen. Wenn nicht angegeben, ist das Standardintervall auf 60 Minuten festgelegt. Zusätzlich bieten wir einen streaming Modus an, der server-sent events (SSE) verwendet, um neue Konfigurationen automatisch an das SDK zu pushen und neue Konfigurationen in Echtzeit ohne Verzögerungen anzuwenden. | 60 |
| Umgebung (optional) | Environment | feature flag-Umgebung | Environment.Production |
| targetingDataCleanupInterval (optional) | number | Intervall in Minuten zum Bereinigen der Targeting-Daten; der Mindestwert beträgt 1 Minute | undefined (keine Bereinigung wird durchgeführt) |
| domain (optional) | string | domain zu der das Cookie gehört. Veraltet, verwenden Sie stattdessen cookieDomain stattdessen | undefined |
| cookieDomain (optional) | string | domain zu der das Cookie gehört. | undefined |
| networkDomain (optional) | string | benutzerdefinierte Domain, die die SDKs für alle ausgehenden Netzwerkanfragen verwenden, häufig für Proxying. Das Format ist second_level_domain.top_level_domain (zum Beispiel, example.com). Wenn ein ungültiges Format angegeben wird, verwendet das SDK den Standardwert von Kameleoon | undefined |
| requestTimeout (optional) | number | Timeout in Millisekunden für alle SDK-Netzwerkanfragen; wenn das Timeout überschritten wird, schlägt die Anfrage sofort fehl | 10_000 (10 Sekunden) |
| trackingInterval (optional) | number | Gibt das Intervall für Tracking-Anfragen in Millisekunden an. Alle Besucher, die für einen feature flag ausgewertet wurden oder zugehörige Daten hatten, werden in diese Tracking-Anfrage aufgenommen, die einmal pro Intervall durchgeführt wird. Der Mindestwert ist 100 ms und der Höchstwert ist 1_000 ms | 1_000 (1 Sekunde) |
The domain Parameter is deprecated and wird removed in a future release. Use cookieDomain stattdessen.
| Name | Typ | Beschreibung | Standardwert |
|---|
| updateInterval (optional) | number | Gibt das Aktualisierungsintervall in Minuten an, in dem das SDK die Konfiguration für die aktiven Experiments und feature flags abruft. Der Wert bestimmt die maximale Zeit, die benötigt wird, um Änderungen wie das Aktivieren oder Deaktivieren von feature flags oder das Starten von Experiments an Ihre Produktionsserver zu übertragen. Wenn nicht angegeben, ist das Standardintervall auf 60 Minuten festgelegt. Zusätzlich bieten wir einen streaming Modus an, der server-sent events (SSE) verwendet, um neue Konfigurationen automatisch an das SDK zu pushen und neue Konfigurationen in Echtzeit ohne Verzögerungen anzuwenden. | 60 |
| Umgebung (optional) | Environment | string | feature flag-Umgebung | Environment.Production |
| targetingDataCleanupInterval (optional) | number | Intervall in Minuten zum Bereinigen der Targeting-Daten; der Mindestwert beträgt 1 Minute | undefined (keine Bereinigung wird durchgeführt) |
| cookieDomain (optional) | string | domain zu der das Cookie gehört. | undefined |
| networkDomain (optional) | string | benutzerdefinierte Domain, die die SDKs für alle ausgehenden Netzwerkanfragen verwenden, häufig für Proxying. Das Format ist second_level_domain.top_level_domain (zum Beispiel, example.com). Wenn ein ungültiges Format angegeben wird, verwendet das SDK den Standardwert von Kameleoon | undefined |
| requestTimeout (optional) | number | Timeout in Millisekunden für alle SDK-Netzwerkanfragen; wenn das Timeout überschritten wird, schlägt die Anfrage sofort fehl | 10_000 (10 Sekunden) |
| trackingInterval (optional) | number | Gibt das Intervall für Tracking-Anfragen in Millisekunden an. Alle Besucher, die für einen feature flag ausgewertet wurden oder zugehörige Daten hatten, werden in diese Tracking-Anfrage aufgenommen, die einmal pro Intervall durchgeführt wird. Der Mindestwert ist 1_000 ms und der Höchstwert ist 5_000 ms | 1_000 (1 Sekunde) |
| stubMode (optional) | boolean | Wenn auf true gesetzt, arbeitet der Client im Stub-Modus und führt keine Operationen aus. In diesem Modus führen alle Methodenaufrufe keine Aktionen aus, sodass keine externen Aktionen oder Nebenwirkungen auftreten. | false |
| defaultDataFile (optional) | string | The defaultDataFile feature ensures the Kameleoon SDK is always READY by providing a fallback Konfiguration when no cached data file exists. Developers can preload a gültig Konfiguration by fetching it from https://sdk-config.kameleoon.eu/v3/<sitecode> and passing it as defaultDataFile during Initialisierung. When a dateModified timestamp (in milliseconds) is bereitgestellt and is newer than the cached version, das SDK will verwenden Sie die Standard datafile stattdessen der cached version. If dateModified is omitted, the Standard datafile is only applied when no cached version exists. This ensures das SDK always has a gültig Konfiguration, whether Standard, cached, or aktualisiert. | undefined |
Option 1 (Recommended): Use JSON.stringify()const dataFileJson = {"configuration":{"consentType":.....,
{"key":"show_car","type":"JSON","value":"{\"make\":\"Porsche\",\"model\":\"911\"}"}},
"dateModified":1752209266000};
const dataFileString = JSON.stringify(dataFileJson);
const configuration = {
updateInterval: 20,
defaultDataFile: dataFileString
};
Option 2: Raw JSON string (escape special characters)const configuration = {
updateInterval: 20,
defaultDataFile: `{"configuration":{"consentType":.....,
{"key":"show_car","type":"JSON","value":"{\\"make\\":\\"Porsche\\",\\"model\\":\\"911\\"}"},
"dateModified":1752209266000}`
};
Rückgabewert
| Typ | Beschreibung |
|---|
KameleoonClient | an Instanz of KameleoonClient. |
Make sure not to use several client instances in one Anwendung as it is not fully unterstützt yet and may overwrite the local Speicher Konfiguration and cause unintended behavior (bugs).
Feature flags and Variationen
Dieser Abschnitt enthält die Methoden, mit denen Sie die dem Besucher zugewiesenen feature flags und Variationen abrufen und verwalten.
getVariation()
- 📨 Sendet Tracking-Daten an Kameleoon (abhängig vom Parameter
track )
Retrieves the Variation assigned to a given Besucher for a specific feature flag.
This Methode takes featureKey as a erforderlich Argument und track as an optional Argument. The track Argument is optional and defaults to true.
It gibt die assigned Variation für den Besucher. If the Besucher is not associated with any feature flag rules, the Methode gibt die Standard Variation für den given feature flag.
Ensure that proper Fehler handling is implemented in your code to manage potential Ausnahmen.
The Standard Variation refers zum Variation assigned to a Besucher when they do not match any vordefiniert delivery rules for a feature flag. In other words, it is the fallback Variation applied to all Benutzer who are not targeted by specific rules. Es ist represented as the Variation im “Then, for everyone else…” Abschnitt in a management interface.
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVariation } = useFeatureFlag();
const { getVisitorCode } = useVisitorCode();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code using `getVisitorCode` function
const visitorCode = getVisitorCode();
// -- Get variation with tracking
const variation = getVariation({
visitorCode,
featureKey: 'my_feature_key',
});
// -- Get variation without tracking
const variation = 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,
// }
// },
// }
}, [initialize, visitorCode, getVariation, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getVariation } = useFeatureFlag();
const { getVisitorCode } = useVisitorCode();
const init = useCallback(async () => {
await initialize();
// -- Get visitor code using `getVisitorCode` function
const visitorCode = getVisitorCode();
// -- Get variation with tracking
const variation = getVariation({
visitorCode,
featureKey: 'my_feature_key',
});
// -- Get variation without tracking
const variation = 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,
// }
// },
// }
}, [initialize, visitorCode, getVariation, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
Argumente
An Objekt of type GetVariationParamsType mit dem following properties:
| Name | Typ | Beschreibung | Standard |
|---|
| visitorCode (required) | string | Eindeutiger Identifikator des Besuchers. | |
| featureKey (required) | string | Schlüssel des Features, das Sie einem Besucher exponieren möchten. | |
| track (optional) | boolean | Ein optionaler Parameter zum Aktivieren oder Deaktivieren des Trackings der Feature-Auswertung. | true |
Rückgabewert
| Typ | Beschreibung |
|---|
Variation | An assigned Variation to a given Besucher for a specific feature flag. |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Die Methode was executed before the kameleoonClient den Aufruf abgeschlossen hat initialize call. |
KameleoonException.VisitorCodeEmpty | Der Visitor-Code ist leer. |
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten. |
KameleoonException.FeatureFlagConfigurationNotFound | Ausnahme indicating that the requested feature key wasn’t found im intern Konfiguration der SDK. This usually means that the feature flag is not activated im Kameleoon app (but code implementing the feature is already deployed im Anwendung). |
KameleoonException.FeatureFlagEnvironmentDisabled | Ausnahme indicating that feature flag is disabled für den Besucher’s aktuell Umgebung (zum Beispiel, production, staging, or development). |
getVariations()
Die Methode is obtained using useFeatureFlag Hook.
Retrieves a map of Variation Objekte assigned to a given Besucher across all feature flags.
This Methode iterates over all verfügbar feature flags and gibt die assigned Variation for each flag associated mit dem specified Besucher. It takes visitorCode as a erforderlich Argument, while onlyActive und track are optional.
- If
onlyActive is set to true, the Methode getVariations() will return feature flags Variationen bereitgestellt the Benutzer is not bucketed mit dem off Variation.
- The
track Parameter controls whether or not the Methode will track the Variation assignments. By Standard, it is set to true. If set to false, the tracking wird disabled.
The returned map consists of feature flag keys as keys and their corresponding Variation as Werte. If no Variation is assigned for a feature flag, the Methode gibt die Standard Variation for that flag.
Proper Fehler handling sollte implemented to manage potential Ausnahmen.
The Standard Variation refers zum Variation assigned to a Besucher when they do not match any vordefiniert delivery rules for a feature flag. In other words, it is the fallback Variation applied to all Benutzer who are not targeted by specific rules. Es ist represented as the Variation im “Then, for everyone else…” Abschnitt in a management interface.
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVariations } = useFeatureFlag();
const { getVisitorCode } = useVisitorCode();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code using `getVisitorCode` function
const visitorCode = getVisitorCode();
// -- Get all feature flag variations with tracking
const variations = getVariations({
visitorCode,
});
// -- Get active feature flag variations with tracking
const variations = getVariations({
visitorCode,
onlyActive: true,
});
// -- Get active feature flag variations without tracking
const variations = 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,
// }
// },
// }
// }
}, [initialize, visitorCode, getVariations, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getVariations } = useFeatureFlag();
const { getVisitorCode } = useVisitorCode();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code using `getVisitorCode` function
const visitorCode = getVisitorCode();
// -- Get all feature flag variations with tracking
const variations = getVariations({
visitorCode,
});
// -- Get active feature flag variations with tracking
const variations = getVariations({
visitorCode,
onlyActive: true,
});
// -- Get active feature flag variations without tracking
const variations = 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,
// }
// },
// }
// }
}, [initialize, visitorCode, getVariations, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
Argumente
An Objekt of type GetVariationsParamsType mit dem following properties:
| Name | Typ | Beschreibung | Standard |
|---|
| visitorCode (required) | string | Eindeutiger Identifikator des Besuchers. | |
| onlyActive (optional) | boolean | An optional Parameter indicating whether to return Variationen for active (true) or all (false) feature flags. | false |
| track (optional) | boolean | Ein optionaler Parameter zum Aktivieren oder Deaktivieren des Trackings der Feature-Auswertung. | true |
Rückgabewert
| Typ | Beschreibung |
|---|
Map<string, Variation> | Map that contains the assigned Variation Objekte der feature flags using the keys der corresponding features. |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Die Methode was executed before the kameleoonClient den Aufruf abgeschlossen hat initialize call. |
KameleoonException.VisitorCodeEmpty | Der Visitor-Code ist leer. |
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten. |
isFeatureFlagActive()
- 📨 Sendet Tracking-Daten an Kameleoon (abhängig vom Parameter
track )
- 🎯 Events:
EventType.Evaluation
The Methode isFeatureFlagActive(), used mit dem useFeatureFlag Hook, determines whether a Besucher identified by visitorCode has the specified featureKey active. This Methode checks the Targeting conditions, identifies the Variation für den Besucher, and saves this Informationen to Speicher. Additionally, the Hook sends a tracking Anfrage.
Es gibt also an overload for this Methode that includes a track Parameter, allowing you to disable the tracking der feature evaluation.
Visitor muss targeted to has feature flag active
Kameleoon uses tracking to count Sitzungen and Besucher when you call certain Methoden, such as isFeatureFlagActive(), getVariation() oder getVariations().Verwenden Sie die Standard true Wert für den track Parameter when you expose Besucher to a Variation and need to count them. Set the track Parameter to false only if you callese Methoden before you expose Besucher.Zum Beispiel, if you call getVariations() to retrieve all Variationen before you expose Besucher, set the track Parameter to false. This setting prevents Kameleoon from prematurely counting a Sitzung. You can then trigger tracking later when you explicitly expose the Besucher.Kameleoon sends tracking data every second by Standard. You can configure this Intervall up to five seconds using the tracking Intervall Konfiguration option. Kameleoon groups tracking events into a single Sitzung as long as the Intervall between events is less than 30 minutes. If more than 30 minutes elapse between tracking events, Kameleoon counts the events as separate Sitzungen. A visit appears in your reports 30 minutes after the last recorded event im Sitzung.
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useData,
useFeatureFlag,
useVisitorCode,
CustomData,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { addData } = useData();
const { isFeatureFlagActive } = useFeatureFlag();
const { getVisitorCode } = useVisitorCode();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code using `getVisitorCode` function
const visitorCode = getVisitorCode();
const featureKey = 'my_feature_key';
// -- Add CustomData with index `0` containing visitor id to check the targeting
addData(visitorCode, new CustomData(0, 'visitor_id'));
// -- Get the status of feature flag
const isActive = isFeatureFlagActive(visitorCode, featureKey);
// -- Check if the feature flag is active for visitor without tracking
const isActive = isFeatureFlagActive({ visitorCode, featureKey: 'my_feature', track: false});
}, [initialize, visitorCode, isFeatureFlagActive, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useData,
useFeatureFlag,
useVisitorCode,
CustomData,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { addData } = useData();
const { isFeatureFlagActive } = useFeatureFlag();
const { getVisitorCode } = useVisitorCode();
const init = useCallback(async () => {
await initialize();
// -- Get visitor code using `getVisitorCode` function.
const visitorCode = getVisitorCode();
const featureKey = 'my_feature_key';
// -- Add CustomData with index `0` containing visitor id to check targeting.
addData(visitorCode, new CustomData(0, 'visitor_id'));
// -- Get the feature flag's status.
const isActive = isFeatureFlagActive(visitorCode, featureKey);
// -- Check if the feature flag is active for visitors without tracking.
const isActive = isFeatureFlagActive({ visitorCode, featureKey: 'my_feature', track: false});
}, [initialize, visitorCode, isFeatureFlagActive, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
Die Methode isFeatureFlagActive() Methode evaluates the served variant, not the master flag state. If you exclude rules, the Methode uses the Then, for everyone else serve Standard state. If you select Off for this Standard state, the Methode always returns false even when the master feature flag is On.
Argumente
Es gibt two overloads verfügbar for this Methode:
- Two Parameter overload:
This overload is deprecated and wird removed im next major version. Please verwenden Sie die new overload with an Objekt Parameter.
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | Eindeutige Besucher-Identifikationszeichenfolge, darf 255 Zeichen nicht überschreiten |
| featureKey (required) | string | ein eindeutiger Schlüssel für den feature flag |
- Objekt Parameter overload of type
IsFeatureFlagActiveParamsType:
| Name | Typ | Beschreibung | Standard |
|---|
| visitorCode (required) | string | Eindeutige Besucher-Identifikationszeichenfolge, darf 255 Zeichen nicht überschreiten | - |
| featureKey (required) | string | ein eindeutiger Schlüssel für den feature flag | - |
| track (optional) | boolean | ein boolescher Indikator dafür, ob die Feature-Auswertung getrackt werden soll | true |
Rückgabewert
| Typ | Beschreibung |
|---|
boolean | indicator of whether the feature flag with featureKey is active for Besucher with visitorCode. |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Die Methode was executed before the kameleoonClient den Aufruf abgeschlossen hat initialize call |
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.FeatureFlagConfigurationNotFound | Es wurde kein feature flag für den angegebenen featureKey |
KameleoonException.DataInconsistency | Eine zugewiesene Variation wurde gefunden, aber es gibt keinen feature flag mit dem entsprechenden featureKey |
setForcedVariation()
The Methode allows you to programmatically assign a specific Variation to a Benutzer, bypassing the standard evaluation process. Dies ist especially valuable for controlled Experiments where the usual evaluation logic is not erforderlich or muss skipped. It can also be helpful in scenarios like debugging or custom testing.
When a erzwungen Variation is set, it überschreibt Kameleoon’s real-time evaluation logic. Processes like Segmentierung, Targeting conditions, and algorithmic calculations are skipped. To preserve Segmentierung and Targeting conditions during an Experiment, set forceTargeting=false stattdessen.
Simulated Variationen always take precedence im execution order. If a simuliert Variation calculation is triggered, it wird fully processed and completed first.
A erzwungen Variation is treated the same as an evaluated Variation. Es ist tracked in analytics and stored im Benutzer Kontext like any standard evaluated Variation, ensuring consistency in reporting.
The Methode may throw Ausnahmen under certain conditions (e.g., ungültig Parameter, Benutzer Kontext, or intern issues). Proper Ausnahme handling is essential to ensure that your Anwendung remains stabil and resilient.
It’s important to distinguish erzwungen Variationen from simuliert Variationen:
- Forced Variationen: Are specific to an individual Experiment.
- Simulated Variationen: Affect the overall feature flag result.
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { setForcedVariation } = useFeatureFlag();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Forcing the variation "on" in the feature flag "featureKey1" for the visitor
setForcedVariation({
visitorCode: visitorCode,
experimentId: 9516,
variationKey: 'on',
forceTargeting: false,
});
// -- Resetting the forced variation for the "featureKey1" feature flag for the visitor
setForcedVariation({
visitorCode: visitorCode,
experimentId: 9516,
variationKey: null,
});
}, [initialize, visitorCode, setForcedVariation, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { setForcedVariation } = useFeatureFlag();
const init = useCallback(async () => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Forcing the variation "on" for the "featureKey1" feature flag for the visitor
setForcedVariation({
visitorCode: visitorCode,
experimentId: 9516,
variationKey: 'on',
forceTargeting: false,
});
// -- Resetting the forced variation for the "featureKey1" feature flag for the visitor
setForcedVariation({
visitorCode: visitorCode,
experimentId: 9516,
variationKey: null,
});
}, [initialize, visitorCode, setForcedVariation, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
Argumente
An Objekt of type SetForcedVariationParametersType mit dem following properties:
| Name | Typ | Beschreibung | Standard | |
|---|
| visitorCode (required) | string | Eindeutiger Identifikator des Besuchers. | | |
| experimentId (required) | number | Experiment Id that wird targeted and selected during the evaluation process. | | |
| variationKey (required) | `string | null` | Variation Key corresponding to a Variation that sollte erzwungen as the returned Wert für den Experiment. If the Wert is null, the erzwungen Variation wird reset. | |
| forceTargeting (optional) | boolean | Indicates whether Targeting für den Experiment sollte erzwungen and skipped (true) or applied as im standard evaluation process (false). | true | |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeEmpty | Der Visitor-Code ist leer. |
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten. |
KameleoonException.Initialization | Indicates that das SDK is not yet fully initialized. |
KameleoonException.FeatureFlagExperimentNotFound | Ausnahme indicating that the requested Experiment id has not been found im SDK’s intern Konfiguration. Dies ist usually normal and means that the rule’s corresponding Experiment has not yet been activated on Kameleoon’s side. |
KameleoonException.FeatureFlagVariationNotFound | Ausnahme indicating that the requested Variation key(id) has not been found im intern Konfiguration der SDK. Dies ist usually normal and means that the Variation’s corresponding Experiment has not yet been activated on Kameleoon’s side. |
KameleoonException.StorageRead | Speicherdaten konnten nicht gelesen werden. |
KameleoonException.StorageWrite | Speicherdaten konnten nicht aktualisiert werden. |
In most cases, only the basic Fehler, KameleoonException, needs to be handled, as demonstrated im example. However, if different types of Fehler require a Antwort, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language Fehler kann handled by including Error.
evaluateAudiences()
- 📨 Sendet Tracking-Daten an Kameleoon
This Methode evaluates Besucher against all verfügbar Audiences Explorer Segmente and tracks those who match.
evaluateAudiences() sollte called after all relevant Besucher data has been set or aktualisiert, and just before getting a feature Variation or checking a feature flag. This approach ensures that the Besucher is evaluated against the most aktuell data verfügbar, allowing for accurate Audience assignment based on all criteria.
After calling this Methode, you can perform a detailed analysis of Segment performance in Audiences Explorer.
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { evaluateAudiences } = useFeatureFlag();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
evaluateAudiences(visitorCode);
}, [initialize, visitorCode, evaluateAudiences, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { evaluateAudiences } = useFeatureFlag();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
evaluateAudiences(visitorCode);
}, [initialize, visitorCode, evaluateAudiences, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
Argumente
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | Eindeutiger Identifikator des Besuchers. |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Die Methode was executed before the kameleoonClient den Aufruf abgeschlossen hat initialize call. |
KameleoonException.VisitorCodeEmpty | Der Visitor-Code ist leer. |
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten. |
In most cases, only the basic Fehler, KameleoonException, needs to be handled, as demonstrated im example. However, if different types of Fehler require a Antwort, handle each one separately based on specific requirements. Additionally, for enhanced reliability, general language Fehler kann handled by including Error.
getDataFile()
To evaluate all feature flags, use getVariations(). This Methode is more efficient than calling DataFile and iterating through flags with getVariation().
Gibt die aktuell SDK Konfiguration as a DataFile Objekt.
import { useEffect, useCallback } from 'react';
import {
useFeatureFlag,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { getDataFile } = useFeatureFlag();
useEffect(() => {
const dataFile = getDataFile();
}, [getDataFile]);
}
import { useEffect, useCallback } from 'react';
import {
useFeatureFlag,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { getDataFile } = useFeatureFlag();
useEffect(() => {
const dataFile = getDataFile();
}, [getDataFile]);
}
Rückgabewert
| Typ | Beschreibung |
|---|
DataFile | The DataFile containing das SDK Konfiguration |
Besucherdaten
Dieser Abschnitt enthält die Methoden, mit denen Sie Besucherdaten verwalten.
getVisitorCode()
getVisitorCode Methode collected from useVisitorCode Hook obtains a visitor code vom Browser Cookie. If the visitor code doesn’t exist yet, the Funktion generates a random visitor code (or uses the defaultVisitorCode Wert if you bereitgestellt one) and sets the new visitor code in a Cookie.
Die Methode getVisitorCode() Methode allows you to set simuliert Variationen for a Besucher. When Cookies (from a Anfrage or document) contaim key kameleoonSimulationFFData, the standard evaluation process is bypassed. Instead, the Methode directly returns a Variation basierend auf dem bereitgestellt data.You can apply simulations in two ways:
- Automatically (recommended): If using Kameleoon Web Experimentation or das SDK in Hybrid mode, the Cookie is created automatically when simulating a variant’s display using the Simulation Panel.
- Manually: Set the
kameleoonSimulationFFData Cookie manually.
It’s important to distinguish simuliert Variationen from erzwungen Variationen:
- Simulated Variationen: Affect the overall feature flag result.
- Forced Variationen: Are specific to an individual Experiment.
⚙️ Manual setupPlease ensure the kameleoonSimulationFFData Cookie follows this Format:
kameleoonSimulationFFData={"featureKey":{"expId":10,"varId":20}}: Simulates the Variation with varId of Experiment expId für den given featureKey.
kameleoonSimulationFFData={"featureKey":{"expId":0}}: Simulates the Standard Variation (defined im Then, for everyone else in Production, serve Abschnitt) für den given featureKey.
⚠️ To ensure proper functionality, the Cookie Wert muss encoded as a URI Komponente using eine Methode such as encodeURIComponent.
import { useEffect, useCallback } from 'react';
import { useInitialize, useVisitorCode } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Pass, save, and retrieve the default visitorCode.
const visitorCode = getVisitorCode('default_visitor_code');
}, [initialize, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize, useVisitorCode } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const init = useCallback(async () => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Pass, save, and retrieve the default visitorCode.
const visitorCode = getVisitorCode('default_visitor_code');
}, [initialize, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
Argumente
| Name | Typ | Beschreibung |
|---|
| defaultVisitorCode (optional) | string | visitor code to be used in case there is no visitor code in Cookies |
If you don’t bereitstellen a defaultVisitorCode and there is no visitor code stored in a Cookie, the visitor code wird randomly generated.
Rückgabewert
| Typ | Beschreibung |
|---|
string | result visitor code. |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | Die Länge des Visitor-Codes wurde überschritten |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
addData()
The addData Funktion, used mit dem useData Hook, collects Targeting data to store for other Hooks to determine if the aktuell Besucher is targeted.
- The
addData() Funktion does not return any Wert and does not interact with Kameleoon Backend servers on its own. Instead, alle declared data is saved for future transmission via the flush Methode .This approach helps reduce the Anzahl of server calls made, as the data is typically grouped into a single server call triggered by the execution of flush.
The trackConversion Methode also sends out any previously associated data, just like the flush. The same holds true for getFeatureFlagVariationKey und getFeatureVariable Methoden if an experimentation rule is triggered.
-
userAgent data will not be stored in Speicher like other data, and it wird sent with every tracking Anfrage for bot filtration.
-
Check the list of unterstützt conditions to know what data types kann wird verwendet für Targeting
Each Besucher can only have one Instanz of associated data for most data types. However, CustomData is an Ausnahme. Visitors can have one Instanz of associated CustomData per customDataIndex.
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useVisitorCode,
useData,
CustomData,
Browser,
BrowserType,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { addData } = useData();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Create Kameleoon Data Types
const customData = new CustomData(0, 'my_data');
const browserData = new Browser(BrowserType.Chrome);
// -- Add a single data item (tracked by default)
addData('my_visitor_code', browserData);
// -- Add multiple data items (tracked by default)
addData('my_visitor_code', browserData, customData);
// -- Add multiple data items from array (tracked by default)
const dataArr = [browserData, customData];
addData('my_visitor_code', ...dataArr);
// -- Add multiple data items stored locally for targeting only (not sent to the Kameleoon Data API)
addData({visitorCode: 'my_visitor_code', track: false, data: dataArr});
}, [initialize, visitorCode, addData, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useVisitorCode,
useData,
CustomData,
Browser,
BrowserType,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { addData } = useData();
const init = useCallback(async () => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Create Kameleoon Data Types
const customData = new CustomData(0, 'my_data');
const browserData = new Browser(BrowserType.Chrome);
// -- Add a single data item (tracked by default)
addData('my_visitor_code', browserData);
// -- Add multiple data items (tracked by default)
addData('my_visitor_code', browserData, customData);
// -- Add multiple data items from array (tracked by default)
const dataArr = [browserData, customData];
addData('my_visitor_code', ...dataArr);
// -- Add multiple data items stored locally for targeting only (not sent to the Kameleoon Data API)
addData({visitorCode: 'my_visitor_code', track: false, data: dataArr});
}, [initialize, visitorCode, addData, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
Argumente
| Name | Typ | Beschreibung | Standardwert |
|---|
| visitorCode (required) | string | Eindeutige Besucher-Identifikationszeichenfolge, darf 255 Zeichen nicht überschreiten. | |
| track (optional) | boolean | Specifies whether the added data is eligible für Tracking. When set to false, the data is stored locally and used only for Targeting evaluation; it is not sent zum Kameleoon Data API. | true |
| kameleoonData (optional) | KameleoonDataType[] | Anzahl of instances of any type of KameleoonData, kann added solely in array or as sequential Argumente | |
-
kameleoonData is variadic Argument it kann passed as one or several Argumente (see the example)
-
The index or ID der Custom Data kann found in your Kameleoon account. Es ist important to note that this index starts at
0, which means that the first Custom Data you create for a given site wird assigned 0 as its ID, not 1.
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.StorageWrite | Speicherdaten konnten nicht aktualisiert werden |
KameleoonException.Initialization | Die Methode was executed before the kameleoonClient den Aufruf abgeschlossen hat initialize call |
See the Data types reference for more details of how to manage different data types.
flush()
SDK Version 9
SDK Version 10
Die Methode flush collected with useData takes the Kameleoon data associated mit dem Besucher and sends the data tracking Anfrage zusammen mit all der data that’s been added previously using the addData.If you don’t specify a visitorCode, das SDK flushes all of its stored data zum remote Kameleoon servers. If any previously failed tracking Anfragen were stored locally during offline Modus, das SDK attempts to send the stored Anfragen before executing the neueste Anfrage.The isUniqueIdentifier Parameter kann nützlich in some edge-case scenarios, such as when you can’t access the anonymous visitorCode that was originally assigned zum Besucher, but you do have access to an intern ID that is connected zum anonymous Besucher using Sitzung Zusammenführen -Funktionen zu empfangen.
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useVisitorCode,
useData,
CustomData,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { addData, flush } = useData();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Create instance of CustomData
const customData = new CustomData(0, 'my_data');
addData(visitorCode, customData);
// -- Flush added custom data for visitor
flush(visitorCode);
// -- Instantly flush added custom data for visitor (fire-and-forget)
flushInstant(visitorCode);
// -- Instantly flush added custom data for visitor and wait for completion
await flushInstant(visitorCode);
// -- Flush data for all the visitors
flush();
// -- Instantly flush data for all the visitors (fire-and-forget)
flushInstant();
// -- Instantly flush data for all the visitors and wait for complention
await flushInstant();
// -- Flush data with unique visitor identifier flag
const internalUserId = 'my_user_id';
flush(internalUserId, true);
}, [initialize, visitorCode, addData, flush, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useVisitorCode,
useData,
CustomData,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { addData, flush } = useData();
const init = useCallback(async () => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Create instance of CustomData
const customData = new CustomData(0, 'my_data');
addData(visitorCode, customData);
// -- Flush added custom data for visitor
flush(visitorCode);
// -- Flush data for all the visitors
flush();
// -- Flush data with unique visitor identifier flag
const internalUserId = 'my_user_id';
flush(internalUserId, true);
}, [initialize, visitorCode, addData, flush, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
Argumente
| Name | Typ | Beschreibung | Standard |
|---|
| visitorCode (optional) | string | Eindeutige Besucher-Identifikationszeichenfolge, darf 255 Zeichen nicht überschreiten, if not passed alle data wird flushed (sent zum remote Kameleoon servers) | - |
| isUniqueIdentifier (optional) | boolean | an optional Parameter for specifying if the visitorCode is a eindeutig Identifikator | false |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.Initialization | Die Methode was executed before the kameleoonClient den Aufruf abgeschlossen hat initialize call |
flush() takes the Kameleoon data associated mit dem Besucher and schedules the data to be sent mit dem next tracking Anfrage. The time der next tracking Anfrage is defined by SDK Konfiguration trackingInterval Parameter. Visitor data kann added using addData und getRemoteVisitorData Methoden.If you don’t specify a visitorCode, das SDK flushes all of its stored data zum remote Kameleoon servers. If any previously failed tracking Anfragen were stored locally during offline Modus, das SDK attempts to send the stored Anfragen before executing the neueste Anfrage.If you need to send tracking Anfragen immediately, use flushInstant() — the asynchronous version of flush that returns Promise<void>. You can await it when you need delivery guarantees (zum Beispiel, before page navigation/unload), or call it without await as a fire-and-forget Anfrage:
await flushInstant(visitorCode) sends tracking Anfragen immediately for a specific Besucher and waits for completion
await flushInstant() sends tracking Anfragen immediately for all Besucher and waits for completion
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useVisitorCode,
useData,
CustomData,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { addData, flush } = useData();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Create instance of CustomData
const customData = new CustomData(0, 'my_data');
addData(visitorCode, customData);
// -- Flush added custom data for visitor
flush(visitorCode);
// -- Instantly flush added custom data for visitor
flush({ visitorCode, instant: true });
// -- Flush data for all the visitors
flush();
// -- Instantly flush data for all the visitors
flush({ instant: true });
}, [initialize, visitorCode, addData, flush, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useVisitorCode,
useData,
CustomData,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { addData, flush } = useData();
const init = useCallback(async () => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Create instance of CustomData
const customData = new CustomData(0, 'my_data');
addData(visitorCode, customData);
// -- Flush added custom data for visitor
flush(visitorCode);
// -- Instantly flush added custom data for visitor
flush({ visitorCode, instant: true });
// -- Flush data for all the visitors
flush();
// -- Instantly flush data for all the visitors
flush({ instant: true });
}, [initialize, visitorCode, addData, flush, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
Argumente
| Name | Typ | Beschreibung | Standard |
|---|
| visitorCode (optional) | string | eindeutig Besucher identification string, can’t exceed 255 characters, if not passed, all data wird flushed (sent zum remote Kameleoon servers). | - |
Or an Objekt mit dem type FlushParamsType, containing:| Name | Typ | Beschreibung | Standard |
|---|
| visitorCode (optional) | string | eindeutig Besucher identification string, can’t exceed 255 characters, if not passed, all data wird flushed (sent zum remote Kameleoon servers). | - |
| instant (optional) | boolean | Boolean flag indicating whether the data sollte sent instantly (true) or according zum scheduled tracking Intervall (false). | - |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.Initialization | Die Methode was executed before the kameleoonClient den Aufruf abgeschlossen hat initialize call |
getRemoteData()
Asynchronous Methode getRemoteData, collected mit dem useData Hook, returns a data stored for specified site code on a remote Kameleoon server.
Zum Beispiel, you can use this Funktion to retrieve Benutzer preferences, historical data, or any other data relevant to your Anwendung’s logic. By storing this data on our highly scalable servers using our [Data API], you can efficiently manage massive amounts of data and retrieve it for each of your Besucher or Benutzer.
import { useEffect, useCallback } from 'react';
import { useData } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { getRemoteData } = useData();
const getData = useCallback(async (): Promise<void> => {
// -- Get remote data
const jsonData = await getRemoteData('my_data_key');
const data = JSON.parse(jsonData);
}, [getRemoteData]);
useEffect(() => {
getData();
}, [getData]);
}
import { useEffect, useCallback } from 'react';
import { useData } from '@kameleoon/react-sdk';
function MyComponent() {
const { getRemoteData } = useData();
const getData = useCallback(async () => {
// -- Get remote data
const jsonData = await getRemoteData('my_data_key');
const data = JSON.parse(jsonData);
}, [getRemoteData]);
useEffect(() => {
getData();
}, [getData]);
}
Argumente
| Name | Typ | Beschreibung |
|---|
| key (required) | string | eindeutig key that the data you try to get is associated with |
Rückgabewert
| Typ | Beschreibung |
|---|
JSONType | promise with data retrieved for specific key. |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.RemoteData | Couldn’t retrieve data from Kameleoon server |
getRemoteVisitorData()
SDK Version 9
SDK Version 10
getRemoteVisitorData() is an asynchronous Methode zum Abrufen Kameleoon Visits Data für den visitorCode vom Kameleoon Data API. The Methode adds the data to Speicher for other Methoden to use when making Targeting decisions.Data obtained using this Methode plays an important role when you want to:
- use data collected from other Geräte.
- access a Benutzer’s Verlauf, such as previously visited pages during past visits.
- use data that is only accessible on the clientseitig, like datalayer Variablen and Ziele that only convert on the Frontend.
Read this Artikel for a better understanding of possible use cases.By Standard, getRemoteVisitorData() automatically retrieves the neueste stored Custom Data with scope=Visitor and attaches them zum Besucher without the need to calle Methode addData(). Es ist particularly nützlich for synchronizing Custom Data between multiple Geräte. The isUniqueIdentifier Parameter kann nützlich in edge-case scenarios, such as when you can’t access the anonymous visitorCode that was originally assigned zum Besucher, but you do have access to an intern ID that is connected zum anonymous Besucher using Sitzung Zusammenführen -Funktionen zu empfangen.
import { useEffect, useCallback } from 'react';
import {
useData,
KameleoonDataType,
VisitorDataFiltersType,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { getRemoteVisitorData } = useData();
const getData = useCallback(async (): Promise<void> => {
// -- 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,
});
}, [getRemoteVisitorData]);
useEffect(() => {
getData();
}, [getData]);
}
import { useEffect, useCallback } from 'react';
import { useData } from '@kameleoon/react-sdk';
function MyComponent() {
const { getRemoteVisitorData } = useData();
const getData = useCallback(async () => {
// -- 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,
});
}, [getRemoteVisitorData]);
useEffect(() => {
getData();
}, [getData]);
}
Argumente
An Objekt mit dem type RemoteVisitorDataParamsType containing:| Name | Typ | Beschreibung | Standardwert |
|---|
| visitorCode (required) | string | Eindeutige Besucher-Identifikationszeichenfolge, darf 255 Zeichen nicht überschreiten | - |
| shouldAddData (optional) | boolean | boolean flag identifying whether the retrieved Custom Data sollte set zum Speicher like addData Methode does | true |
| filters (optional) | VisitorDataFiltersType | filters for specifying what data sollte retrieved from visits, by Standard only customData is retrieved vom aktuell and neueste previous visit | { previousVisitAmount: 1, currentVisit: true customData: true }, other filters Parameter are set to false |
| isUniqueIdentifier (optional) | boolean | optional Parameter that, when true, specifies that the visitorCode is a eindeutig Identifikator | false |
Rückgabewert
| Typ | Beschreibung |
|---|
KameleoonDataType[] | promise with list of Kameleoon Data retrieved |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.RemoteData | Couldn’t retrieve data from Kameleoon server |
KameleoonException.VisitAmount | Visit amount muss a Anzahl between 1 and 25 |
KameleoonException.Initialization | Die Methode was executed before initialize was done for kameleoonClient |
Using Parameter in getRemoteVisitorData()
Die Methode getRemoteVisitorData() Methode offers flexibility by allowing you to define various Parameter when retrieving data on Besucher. Whether you’re Targeting based on Ziele, Experiments, or Variationen, the same approach applies across all data types.Zum Beispiel, let’s say you want to retrieve data on Besucher who completed a Ziel “Order transaction”. You can specify Parameter withim getRemoteVisitorData() Methode to refine your Targeting. For Instanz, if you want to target only Benutzer who converted on the Ziel imir last five visits, you can set the previousVisitAmount Parameter to 5 und conversions to true.The flexibility shown in this example is not limited to Ziel data. You can use Parameter withim getRemoteVisitorData() Methode to retrieve data on a variety of Besucher behaviors.Here is the list of verfügbar VisitorDataFiltersType filters:| Name | Typ | Beschreibung | Standard |
|---|
| previousVisitAmount (optional) | number | Number of previous visits to retrieve data from. Number between 1 und 25 | 1 |
| currentVisit (optional) | boolean | If true, aktuell visit data wird retrieved | true |
| customData (optional) | boolean | If true, Custom Data wird retrieved. | true |
| pageViews (optional) | boolean | If true, page data wird retrieved. | false |
| geolocation (optional) | boolean | If true, geolocation data wird retrieved. | false |
| Gerät (optional) | boolean | If true, Gerät 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. Requires the AI Predictive Targeting add-on | false |
getRemoteVisitorData() is an asynchronous Methode zum Abrufen Kameleoon Visits Data für den visitorCode vom Kameleoon Data API. The Methode adds the data to Speicher for other Methoden to use when making Targeting decisions.Data obtained using this Methode plays an important role when you want to:
- use data collected from other Geräte.
- access a Benutzer’s Verlauf, such as previously visited pages during past visits.
- use data that is only accessible on the clientseitig, like datalayer Variablen and Ziele that only convert on the Frontend.
Read this Artikel for a better understanding of possible use cases.By Standard, getRemoteVisitorData() automatically retrieves the neueste stored Custom Data with scope=Visitor and attaches them zum Besucher without the need to calle Methode addData(). Es ist particularly nützlich for synchronizing Custom Data between multiple Geräte. import { useEffect, useCallback } from 'react';
import {
useData,
KameleoonDataType,
VisitorDataFiltersType,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { getRemoteVisitorData } = useData();
const getData = useCallback(async (): Promise<void> => {
// -- 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,
});
}, [getRemoteVisitorData]);
useEffect(() => {
getData();
}, [getData]);
}
import { useEffect, useCallback } from 'react';
import { useData } from '@kameleoon/react-sdk';
function MyComponent() {
const { getRemoteVisitorData } = useData();
const getData = useCallback(async () => {
// -- 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,
});
}, [getRemoteVisitorData]);
useEffect(() => {
getData();
}, [getData]);
}
Argumente
An Objekt mit dem type RemoteVisitorDataParamsType containing:| Name | Typ | Beschreibung | Standardwert |
|---|
| visitorCode (required) | string | Eindeutige Besucher-Identifikationszeichenfolge, darf 255 Zeichen nicht überschreiten | - |
| shouldAddData (optional) | boolean | boolean flag identifying whether the retrieved Custom Data sollte set zum Speicher like addData Methode does | true |
| filters (optional) | VisitorDataFiltersType | filters for specifying what data sollte retrieved from visits, by Standard only customData is retrieved vom aktuell and neueste previous visit | { previousVisitAmount: 1, currentVisit: true customData: true }, other filters Parameter are set to false |
Rückgabewert
| Typ | Beschreibung |
|---|
KameleoonDataType[] | promise with list of Kameleoon Data retrieved |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.RemoteData | Couldn’t retrieve data from Kameleoon server |
KameleoonException.VisitAmount | Visit amount muss a Anzahl between 1 and 25 |
KameleoonException.Initialization | Die Methode was executed before initialize was done for kameleoonClient |
Using Parameter in getRemoteVisitorData()
Die Methode getRemoteVisitorData() Methode offers flexibility by allowing you to define various Parameter when retrieving data on Besucher. Whether you’re Targeting based on Ziele, Experiments, or Variationen, the same approach applies across all data types.Zum Beispiel, let’s say you want to retrieve data on Besucher who completed a Ziel “Order transaction”. You can specify Parameter withim getRemoteVisitorData() Methode to refine your Targeting. For Instanz, if you want to target only Benutzer who converted on the Ziel imir last five visits, you can set the previousVisitAmount Parameter to 5 und conversions to true.The flexibility shown in this example is not limited to Ziel data. You can use Parameter withim getRemoteVisitorData() Methode to retrieve data on a variety of Besucher behaviors.Here is the list of verfügbar VisitorDataFiltersType filters:| Name | Typ | Beschreibung | Standard |
|---|
| previousVisitAmount (optional) | number | Number of previous visits to retrieve data from. Number between 1 und 25 | 1 |
| currentVisit (optional) | boolean | If true, aktuell visit data wird retrieved | true |
| customData (optional) | boolean | If true, Custom Data wird retrieved. | true |
| pageViews (optional) | boolean | If true, page data wird retrieved. | false |
| geolocation (optional) | boolean | If true, geolocation data wird retrieved. | false |
| Gerät (optional) | boolean | If true, Gerät 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. Requires the AI Predictive Targeting add-on | false |
| visitorCode (optional) | boolean | If true, Kameleoon will retrieve the visitorCode vom most recent visit and use it für den aktuell visit. Dies ist necessary if you want to ensure that the Besucher, identified by their visitorCode, always receives the same Variation across visits for Cross-Gerät experimentation. | true |
| personalization (optional) | boolean | If true, personalization data wird retrieved. Dies ist erforderlich für den personalization condition | false |
| cbs (optional) | boolean | If true, Contextual Bandit score data wird retrieved. | false |
getVisitorWarehouseData()
Asynchronous Methode getVisitorWarehouseAudience collected with useData Hook retrieves all Audience data associated mit dem Besucher in your data warehouse using the specified visitorCode und warehouseKey. The warehouseKey is typically your intern Benutzer ID. The customDataIndex Parameter corresponds zum Kameleoon Custom Data that Kameleoon uses to target your Besucher. Refer zum warehouse Targeting documentation for additional details.
import { useEffect, useCallback } from 'react';
import { useData, CustomData } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { getVisitorWarehouseAudience } = useData();
const getData = useCallback(async (): Promise<void> => {
// -- 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,
});
}, [getRemoteData]);
useEffect(() => {
getData();
}, [getData]);
}
import { useEffect, useCallback } from 'react';
import { useData } from '@kameleoon/react-sdk';
function MyComponent() {
const { getVisitorWarehouseAudience } = useData();
const getData = useCallback(async () => {
// -- 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,
});
}, [getRemoteData]);
useEffect(() => {
getData();
}, [getData]);
}
Argumente
Parameters Objekt consisting of:
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | Eindeutige Besucher-Identifikationszeichenfolge, darf 255 Zeichen nicht überschreiten |
| customDataIndex (required) | number | Anzahl representing the index der Custom Data you want to use to target your Warehouse Audiences |
| warehouseKey (optional) | string | eindeutig key to identify the warehouse data (usually, your intern Benutzer ID) |
Rückgabewert
| Typ | Beschreibung |
|---|
Promise<CustomData | null> | promise containing CustomData mit dem associated warehouse data oder null if there was no data |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.RemoteData | Couldn’t retrieve data from Kameleoon server |
setLegalConsent()
Die Methode setLegalConsent, collected with useVisitorCode Hook, specifies whether the Besucher has given legal consent to use personal data. Setting the legalConsent Parameter to false limits the types of data that you can include in tracking Anfragen. This helps you adhere to legal and regulatory requirements while responsibly managing Besucher data. You can find weitere Informationen on personal data im consent management policy.
- Consent Informationen is in sync between the Kameleoon Engine (Anwendung file engine.js) and the React SDK. This Synchronisierung means that once consent is set 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 with Benutzer preferences.
If you use Kameleoon in Hybrid mode, we recommend reading the consent Abschnitt in our Hybrid experimentation Artikel
- When handling legal consent, it’s important to use
getVisitorCode Methode. Additionally, getVisitorCode does not accept domain as an Argument. Instead, pass it zum createClient Funktion.
import { useEffect, useCallback } from 'react';
import { useInitialize, useVisitorCode } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVisitorCode, setLegalConsent } = useVisitorCode();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
setLegalConsent(visitorCode, true);
}, [initialize, getVisitorCode, setLegalConsent]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize, useVisitorCode } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getVisitorCode, setLegalConsent } = useVisitorCode();
const init = useCallback(async () => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
setLegalConsent(visitorCode, true);
}, [initialize, getVisitorCode, setLegalConsent]);
useEffect(() => {
init();
}, [init]);
}
Argumente
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | Eindeutige Besucher-Identifikationszeichenfolge, darf 255 Zeichen nicht überschreiten |
| consent (required) | boolean | a boolean Wert representing the legal consent status. true indicates the Besucher has given legal consent, false indicates the Besucher has never bereitgestellt, or has withdrawn, legal consent |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | The visitor code length exceeded the maximum length (255 characters) |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
Consent revocation behavior
When you call setLegalConsent() with consent=false, das SDK does not delete the kameleoonVisitorCode Cookie. Instead, it stops extending the Cookie’s expiration date, allowing the Cookie to persist until it naturally expires.
If your compliance requirements demand the immediate removal der Cookie file upon opt-out, you must delete it manually using your framework’s nativ Cookie management Methoden. The SDK will not remove the file automatically.
Goals and third-party analytics
This Abschnitt bietet the Methoden you use to track when a Besucher action achieve one of you Ziele (a Konversion).
trackConversion()
SDK Version 9
SDK Version 10
- _📨 Sendet Tracking-Daten an Kameleoon
Die Methode trackConversion() Funktion, used mit dem useData Hook creates and adds Conversion data zum Besucher with specified Parameter and executes flush().Use this Methode to track a Konversion for a specific Ziel and Benutzer. This Methode requires visitorCode und goalId. In addition, this Methode also accepts an optional revenue Argument. The visitorCode is usually identical zum one that was used when triggering the Experiment.Die Methode trackConversion() Methode doesn’t return any Wert. This Methode is non-blocking as the server call is made asynchronously.If you specify a visitorCode and set isUniqueIdentifier to true, the trackConversion() Methode uses it as the eindeutig Besucher Identifikator, which is nützlich for cross-Gerät experimentation becaverwenden Sie die SDK links the flushed data mit dem Besucher that is associated mit dem specified Identifikator.The isUniqueIdentifier can also be nützlich in other edge-case scenarios, such as when you can’t access the anonymous visitorCode that was originally assigned zum Besucher, but you do have access to an intern ID that is connected zum anonymous Besucher using Sitzung Zusammenführen -Funktionen zu empfangen.
import { useEffect, useCallback } from 'react';
import { useInitialize, useVisitorCode, useData } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { trackConversion } = useData();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Track conversion
trackConversion({ visitorCode, revenue: 2000, goalId: 123 });
// -- Track conversion with unique visitor identifier flag
const internalUserId = 'my_user_id';
trackConversion({
visitorCode: internalUserId,
revenue: 20000,
goalId: 123,
isUniqueIdentifier: true,
});
}, [initialize, trackConversion, visitorCode, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize, useVisitorCode, useData } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { trackConversion } = useData();
const init = useCallback(async () => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Track conversion
trackConversion({ visitorCode, revenue: 2000, goalId: 123 });
// -- Track conversion with unique visitor identifier flag
const internalUserId = 'my_user_id';
trackConversion({
visitorCode: internalUserId,
revenue: 20000,
goalId: 123,
isUniqueIdentifier: true,
});
}, [initialize, trackConversion, visitorCode, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
Argumente
Parameters Objekt consisting of:| Name | Typ | Beschreibung | Standard |
|---|
| visitorCode (required) | string | Eindeutiger Identifikator des Besuchers. | |
| goalId (required) | number | ID der Ziel. | |
| revenue (optional) | number | Revenue der Konversion. | 0 |
| isUniqueIdentifier (optional) | boolean | An optional Parameter for specifying if the visitorCode is a eindeutig Identifikator. | false |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten. |
KameleoonException.VisitorCodeEmpty | Der Visitor-Code ist leer. |
KameleoonException.StorageWrite | Speicherdaten konnten nicht aktualisiert werden. |
- 📨 Sendet Tracking-Daten an Kameleoon
Die Methode trackConversion() Funktion, used mit dem useData Hook creates and adds Conversion data zum Besucher with specified Parameter and executes flush().Use this Methode to track a Konversion for a specific Ziel and Benutzer. This Methode requires visitorCode und goalId. In addition, this Methode also accepts an optional revenue, negative und metadata Argumente. The visitorCode is usually identical zum one that was used when triggering the Experiment.Die Methode trackConversion() Methode doesn’t return any Wert. This Methode is non-blocking as the server call is made asynchronously.import { useEffect, useCallback } from 'react';
import { useInitialize, useVisitorCode, useData, CustomData } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { trackConversion } = useData();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Track conversion
trackConversion({
visitorCode,
revenue: 2000,
goalId: 123,
metadata: [new CustomData(0, 'value')],
negative: true,
});
}, [initialize, trackConversion, visitorCode, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize, useVisitorCode, useData, CustomData } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { trackConversion } = useData();
const init = useCallback(async () => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Track conversion
trackConversion({
visitorCode,
revenue: 2000,
goalId: 123,
metadata: [new CustomData(0, 'value')],
negative: true,
});
}, [initialize, trackConversion, visitorCode, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
Argumente
Parameters Objekt consisting of:| Name | Typ | Beschreibung | Standard |
|---|
| visitorCode (required) | string | Eindeutiger Identifikator des Besuchers. | |
| goalId (required) | number | ID der Ziel. | |
| negative (optional) | boolean | Defines if the revenue is positive or negative. | false |
| revenue (optional) | number | Revenue der Konversion. | 0 |
| metadata (optional) | CustomData[] | Metadata der Konversion. Must be defined beforehand im Kameleoon App. | undefined |
metadata Werte are accessible through raw data exports und the results page.If the metadata Parameter is bereitgestellt, Kameleoon will verwenden Sie diese specified Werte für den aktuell Konversion stattdessen of what was previously collected using the addData() Methode. If the Parameter is omitted, Kameleoon will verwenden Sie die last tracked Werte for those CustomData prior zum Konversion and withim same visit.Kameleoon will only consider the metadata Werte that are explicitly passed as Parameter zum trackConversion() Methode.In the example below, Kameleoon will associate the Konversion only mit dem Custom Data Wert explicitly bereitgestellt as a Parameter (here: index 5 mit dem Wert ‘Amex Credit Card’).addData(visitorCode, new CustomData(5, 'Credit Card'), new CustomData(9, 'Express Delivery'));
trackConversion({
visitorCode,
goalId: 1000,
metadata: [new CustomData(5, 'Amex Credit Card')]
});
addData(visitorCode, new CustomData(5, 'Credit Card'), new CustomData(9, 'Express Delivery'));
trackConversion({
visitorCode,
goalId: 1000,
metadata: [new CustomData(5, 'Amex Credit Card')]
});
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten. |
KameleoonException.VisitorCodeEmpty | Der Visitor-Code ist leer. |
KameleoonException.StorageWrite | Speicherdaten konnten nicht aktualisiert werden. |
getEngineTrackingCode()
Kameleoon integrates with several analytics solutions, including Mixpanel, Google Analytics 4, and Segment. To track serverseitig Experiments correctly, calle getEngineTrackingCode() Methode after the Besucher triggers an Experiment. The SDK returns JavaScript queue commands für den Experiments that the Besucher triggered during the previous five seconds. When you insert this code inzum page, Engine.js processes the commands and sends the exposure events through the active analytics integration.
Refer to hybrid experimentation für weitere Informationen on implementing this Methode.
import { useEffect, useCallback } from 'react';
import { useInitialize, useFeatureFlag } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getEngineTrackingCode, getVariation } =
useFeatureFlag();
const [engineCode, setEngineCode] = useState<string>('');
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Trigger feature experiment
// -- E.g., result `variationKey` id is `200` and implicit experiment id is `100`
getVariation({ visitorCode: 'visitor_code', featureKey: 'my_feature_key' });
// -- Get tracking code and set it to state
setEngineCode(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]);
// `
}, [initialize, getVariation, getEngineTrackingCode]);
useEffect(() => {
init();
}, [init]);
useEffect(() => {
if (!engineCode) {
return;
}
// -- Insert tracking code into the page
const script = document.createElement('script');
script.textContent = engineCode;
document.body.appendChild(script);
// -- Remove script from the page
return () => {
document.body.removeChild(script);
};
}, [engineCode]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize, useFeatureFlag } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getEngineTrackingCode, getVariation } =
useFeatureFlag();
const [engineCode, setEngineCode] = useState('');
const init = useCallback(async () => {
await initialize();
// -- Trigger feature experiment
// -- E.g., result `variationKey` id is `200` and implicit experiment id is `100`
getVariation({ visitorCode: 'visitor_code', featureKey: 'my_feature_key' });
// -- Get tracking code and set it to state
setEngineCode(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]);
// `
}, [initialize, getVariation, getEngineTrackingCode]);
useEffect(() => {
init();
}, [init]);
useEffect(() => {
if (!engineCode) {
return;
}
// -- Insert tracking code into the page
const script = document.createElement('script');
script.textContent = engineCode;
document.body.appendChild(script);
// -- Remove script from the page
return () => {
document.body.removeChild(script);
};
}, [engineCode]);
}
-
To use this feature, implement both the React SDK and Kameleoon Engine.js. Because Engine.js is used only für Tracking in this flow, you can installe asynchronous tag before the closing
</body> tag.
-
You can insert the returned tracking code directly into an HTML
<script> tag.
<html lang="en">
<body>
<script>
const engineTrackingCode = `
window.kameleoonQueue = window.kameleoonQueue || [];
window.kameleoonQueue.push(['Experiments.assignVariation', 123456, 7890, true]);
window.kameleoonQueue.push(['Experiments.trigger', 123456, true]);
window.kameleoonQueue.push(['Experiments.assignVariation', 234567, 8901, true]);
window.kameleoonQueue.push(['Experiments.trigger', 234567, true]);
`;
const script = document.createElement('script');
script.textContent = engineTrackingCode;
document.body.appendChild(script);
</script>
</body>
</html>
In this example, 123456 und 234567 are Experiment IDs, und 7890 und 8901 are Variation IDs. In your implementation, das SDK generates these Werte im returned tracking code.
Argumente
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | Eindeutiger Identifikator des Besuchers. |
Rückgabewert
| Typ | Beschreibung |
|---|
string | JavaScript code to insert inzum page. |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
Events
This Abschnitt bietet the Methoden you use to handle events.
onEvent()
Die Methode onEvent, collected mit dem useInitialize Hook, fires a Callback when a specific event is triggered. The Callback Funktion has access zum data associated mit dem event. The SDK Methoden in this documentation note which event types they can trigger, if any.import { useEffect, useCallback } from 'react';
import {
useInitialize,
EventType,
EvaluationEventDataType,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize, onEvent } = useInitialize();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Define logic to execute on SDK event
onEvent(EventType.Evaluation, (eventData: EventDataType) => {
// -- My Logic
});
}, [initialize, onEvent]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize, EventType } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize, onEvent } = useInitialize();
const init = useCallback(async () => {
await initialize();
// -- Define logic to execute on SDK event
.onEvent(EventType.Evaluation, (eventData) => {
// -- My Logic
});
}, [initialize, onEvent]);
useEffect(() => {
init();
}, [init]);
}
You can only assign one Callback to each EventType.
Events
Events are defined im EventType enum. Depending on the event type, the eventData Parameter will have a different type.| Typ | eventData type | Beschreibung |
|---|
EventType.Evaluation | EvaluationEventDataType | Triggered when das SDK evaluates any Variation for a feature flag. Es ist triggered regardless der result Variation |
EventType.ConfigurationUpdate | ConfigurationUpdateEventDataType | Triggered when das SDK receives a Konfiguration aktualisieren vom server (when using real-time streaming) |
Argumente
| Name | Typ | Beschreibung |
|---|
| event (required) | EventType | a type der event to associate the Callback action with |
| Callback (required) | (eventData: EventDataType<EventType>) => void | a Callback Funktion mit dem eventData Parameter that wird called when a Konfiguration aktualisieren occurs |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Die Methode was executed before the kameleoonClient den Aufruf abgeschlossen hat initialize call |
Senden von Expositionsereignissen an externe Tools
Kameleoon bietet integrierte Integrationen mit verschiedenen Analyse- und CDP-Lösungen wie Mixpanel, Google Analytics 4, Segment…. Um sicherzustellen, dass Sie Ihre serverseitigen Experiments tracken und analysieren können, bietet Kameleoon eine Methode getEngineTrackingCode() , die den JavaScript-Code zurückgibt, der in Ihre Seite eingefügt werden soll, um die Expositionsereignisse automatisch an die von Ihnen verwendete Analyselösung zu senden. Das SDK erstellt einen Tracking-Code für Ihre aktive Analyselösung basierend auf den Experiments, die der Besucher in den letzten 5 Sekunden ausgelöst hat.
Weitere Informationen zur Hybrid-Experimentation finden Sie in dieser documentation.Um von dieser Funktion zu profitieren, müssen Sie sowohl das React SDK als auch unseren Kameleoon JavaScript-Tag implementieren. Wir empfehlen, den [Kameleoon asynchronous tag] zu implementieren, den Sie vor Ihrem schließenden <body> -Tag in Ihre HTML-Seite einfügen können, da er nur für Tracking-Zwecke verwendet wird.
Data types
Kameleoon Data types sind Hilfsklassen, die zum Speichern von Daten im Speicher in vordefinierten Formen verwendet werden.
During the flush execution, das SDK collects alle data and sends it along mit dem tracking Anfrage.
Daten, die im SDK verfügbar sind, stehen für Targeting und Reporting in der Kameleoon-App erst dann zur Verfügung, wenn Sie die Daten hinzufügen. Beispielsweise mithilfe der Methode addData() Methode.
See use visit history to target users für weitere Informationen.
Wenn Sie den Hybrid mode verwenden, können Sie getRemoteVisitorData() aufrufen, um automatisch alle Daten zu füllen, die Kameleoon zuvor gesammelt hat.
Browser
Seit React SDK 10.11.0, Browser wird automatisch basierend auf dem User-Agent -String erkannt. Bei Bedarf können Sie dies jedoch manuell überschreiben.
Browser contains Browser Informationen.
Each Besucher can only have one Browser. Adding a second Browser overwrites the first one.
| Name | Typ | Beschreibung |
|---|
| Browser (required) | BrowserType | vordefiniert Browser type (Chrome, InternetExplorer, Firefox, Safari, Opera, Other) |
| version (optional) | number | version der Browser, floating point Anzahl represents major and minor version der Browser |
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useData,
Browser,
BrowserType,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Add new browser data to client
const browser = new Browser(BrowserType.Chrome, 86.1);
addData('my_visitor_code', browser);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useData,
Browser,
BrowserType,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async () => {
await initialize();
// -- Add new browser data to client
const browser = new Browser(BrowserType.Chrome, 86.1);
addData('my_visitor_code', browser);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
UniqueIdentifier
UniqueIdentifier data is used as marker for eindeutig Besucher identification.
If you add UniqueIdentifier for a Besucher, visitorCode is used as the eindeutig Besucher Identifikator, which is nützlich for Cross-Gerät experimentation. Associating a UniqueIdentifier with a Besucher notify SDK that the Besucher is linked to another Besucher.
The UniqueIdentifier can also be nützlich in other edge-case scenarios, such as when you can’t access the anonymous visitorCode that was originally assigned zum Besucher, but you do have access to an intern ID that is connected zum anonymous Besucher using Sitzung Zusammenführen -Funktionen zu empfangen.
Each Besucher can only have one UniqueIdentifier. Adding another UniqueIdentifier overwrites the first one.
| Name | Typ | Beschreibung |
|---|
| Wert (required) | boolean | Wert that specifies if the Besucher is associated with another Besucher, bereitgestellt false will imply that the Besucher is not associated with any other Besucher |
import { useEffect, useCallback } from 'react';
import { useInitialize, useData, UniqueIdentifier } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Add new unique identifier to a visitor
addData('my_visitor_code', new UniqueIdentifier(true));
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize, useData, UniqueIdentifier } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async () => {
await initialize();
// -- Add new unique identifier to a visitor
addData('my_visitor_code', new UniqueIdentifier(true));
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
Konversion
The Conversion data set stored here kann wird verwendet, um filter Experiment and personalization reports by any Ziel associated with it.
- Each Besucher can have multiple
Conversion Objekte.
- You can find the
goalId im Kameleoon app.
ConversionParametersType conversionParameters - an Objekt with Konversion Parameter described below
| Name | Typ | Beschreibung | Standard |
|---|
| goalId (required) | number | ID der Ziel. | |
| revenue (optional) | float | Revenue der Konversion | 0 |
| negative (optional) | boolean | Defines if the revenue is positive or negative. | false |
| metadata (optional) | CustomData[] | Metadata der Konversion. | undefined |
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useData,
Conversion,
ConversionParametersType,
CustomData,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async (): Promise<void> => {
await 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);
addData('my_visitor_code', conversion);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize, useData, Conversion, CustomData } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async () => {
await 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);
addData(visitorCode, conversion);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
Cookie
Cookie contains Informationen about the Cookie stored on the Besucher’s Gerät.
-
Generally, the React SDK will attempt to use a
localStorage Cookie für den conditions. If not possible, SDK can use Cookie data as an alternative.
-
Each Besucher can only have one
Cookie. Adding a second Cookie overwrites the first one.
| Name | Typ | Beschreibung |
|---|
| Cookie (required) | CookieType[] | A list of CookieType Objekte consisting of Cookie keys and Werte |
import {
KameleoonClient,
CookieType,
Cookie,
useInitialize,
useData,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async (): Promise<void> => {
await 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);
addData('my_visitor_code', cookie);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
import {
KameleoonClient,
CookieType,
Cookie,
useInitialize,
useData,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async () => {
await 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);
addData('my_visitor_code', cookie);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
Methoden
Cookie data has a static utility Methode fromString that you can use to create a Cookie instantly by parsing a string that contains gültig Cookie data.
The Methode accepts string as Parameter and returns an initialized Cookie Instanz.
import { Cookie } from '@kameleoon/react-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/react-sdk';
const cookieString = 'key_1=value_1; key_2=value_2';
const cookie = Cookie.fromString(cookieString);
// -- The result cookie will contain the following cookie array
// [
// { key: 'key_1', value: 'value_1' },
// { key: 'key_2', value: 'value_2' },
// ]
GeolocationData
GeolocationData contains the Besucher’s geolocation details
Each Besucher can only have one GeolocationData. Adding a second GeolocationData overwrites the first one.
An Objekt Parameter mit dem type GeolocationInfoType containing the following fields:
| Name | Typ | Beschreibung |
|---|
| country (required) | string | The country der Besucher |
| region (optional) | string | The region der Besucher |
| city (optional) | string | The city der Besucher |
| postalCode (optional) | string | The postal code der Besucher |
| coordinates (optional) | [number, number] | Coordinates array tuple of two position Werte (longitude and latitude). Coordinate Anzahl represents decimal degrees |
import {
KameleoonClient,
GeolocationData,
GeolocationInfoType,
useData,
useInitialize,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async (): Promise<void> => {
await 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);
addData('my_visitor_code', geolocationData);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
import {
KameleoonClient,
GeolocationData,
useData,
useInitialize,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async () => {
await 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);
addData('my_visitor_code', geolocationData);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
CustomData
To retain Custom Data for future visits, das SDK transmits CustomData with a Visitor scope during the next tracking Anfrage. You can configure the scope im data settings on the Custom Data dashboard.
CustomData allows you to associate any type of data with each Besucher easily. This data can then be used as a Targeting condition in Segmente or as a filter or breakdown in Experiment reports.
For weitere Informationen about Custom Data, please refer to this Artikel.
| Name | Typ | Beschreibung | Standard |
|---|
| index/name (required) | number/string | Index or Name der Custom Data. Either index oder name muss bereitgestellt to identify the data. | |
| overwrite (optional) | boolean | Flag to explicitly control how the Werte are stored and how they appear in reports. See more | true |
| Wert (required) | string[] | The Custom Data Wert. It muss stringified to match the string type. Note: Wert is variadic. | |
-
Each Besucher is allowed only one
CustomData for each eindeutig index. Adding another CustomData mit dem same index will replace the existing one.
-
The Custom Data ‘index’ kann found im Custom Data dashboard under the “INDEX” column.
-
To prevent das SDK from sending data mit dem selected index to Kameleoon servers for privacy reasons, enable the option: Use this data only locally for Targeting purposes when creating Custom Data.
-
Adding a
CustomData Instanz created with a name when das SDK Instanz is not initialized or the name is not registered, will result im data being ignored.
import { useEffect, useCallback } from 'react';
import { useInitialize, useData, CustomData } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Defined conversion parameters
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 new custom data to client
addData('my_visitor_code', customData);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize, useData, CustomData } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async () => {
await initialize();
// -- Defined conversion parameters
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 new custom data to client
addData('my_visitor_code', customData);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
Device
Seit React SDK 10.11.0, Device wird automatisch basierend auf dem User-Agent -String erkannt. Bei Bedarf können Sie dies jedoch manuell überschreiben.React Native: Support for this feature is aktuell experimental and may require adjustments to work correctly. In React Native, the Device wird automatisch basierend auf dem DPI from react-native.Dimensions.
Device contains Informationen about your Gerät.
Each Besucher can only have one Device. Adding a second Device overwrites the first one.
| Name | Typ | Beschreibung |
|---|
| deviceType (required) | DeviceType | possible types for Gerät type (PHONE, TABLET, DESKTOP) |
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useData,
Device,
DeviceType,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Add new device data to client
const device = new Device(DeviceType.Desktop);
addData('my_visitor_code', device);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useData,
Device,
DeviceType,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async () => {
await initialize();
// -- Add new device data to client
const device = new Device(DeviceType.Desktop);
addData('my_visitor_code', device);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
OperatingSystem
Seit React SDK 10.11.0, OperatingSystem wird automatisch basierend auf dem User-Agent -String erkannt. Bei Bedarf können Sie dies jedoch manuell überschreiben.React Native: Support for this feature is aktuell experimental and may require adjustments to work correctly. In React Native, the OperatingSystem wird automatisch basierend auf dem react-native.Platform.
OperatingSystem contains the Besucher’s operating system Informationen.
Each Besucher can only have one OperatingSystem. Adding a second OperatingSystem overwrites the previous one.
| Name | Typ | Beschreibung |
|---|
| operatingSystem (required) | OperatingSystemType | possible types for Gerät type: WINDOWS_PHONE, WINDOWS, ANDROID, LINUX, MAC, IOS |
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useData,
OperatingSystem,
OperatingSystemType,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Add operating system data
const operatingSystem = new OperatingSystem(OperatingSystemType.Windows);
addData('my_visitor_code', operatingSystem);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useData,
OperatingSystem,
OperatingSystemType,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async () => {
await initialize();
// -- Add operating system data
const operatingSystem = new OperatingSystem(OperatingSystemType.Windows);
addData('my_visitor_code', operatingSystem);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
PageView
Seit React SDK 10.11.0, PageView wird automatisch basierend auf dem window.location?.href und document.title. However, you can still manually überschreiben it falls erforderlich.React Native: Support for this feature is aktuell experimental and may require adjustments to work correctly.
PageView contains Informationen about your web page.
Each Besucher can have one PageView per eindeutig URL. Adding a PageView mit dem same URL as an existing one will notify SDK that the Besucher revisited page
PageViewParametersType pageViewParameters - an Objekt with page view Parameter described below
| Name | Typ | Beschreibung |
|---|
| urlAddress (required) | string | url address der page to track |
| title (required) | string | title der web page |
| referrer (optional) | number[] | an optional Parameter containing a list of referrers Indices, has no Standard Wert |
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useData,
PageView,
PageViewParametersType,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Define page view parameters
const pageViewParameters: PageViewParametersType = {
urlAddress: 'www.example.com',
title: 'my example',
referrers: [123, 456],
};
// -- Add new page view data to client
const pageView = new PageView(pageViewParameters);
addData('my_visitor_code', pageView);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize, useData, PageView } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async () => {
await initialize();
// -- Define page view parameters
const pageViewParameters = {
urlAddress: 'www.example.com',
title: 'my example',
referrers: [123, 456],
};
// -- Add new page view data to client
const pageView = new PageView(pageViewParameters);
addData('my_visitor_code', pageView);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
UserAgent
Store Informationen on the Benutzer-agent der Besucher. Server-side Experiments are more vulnerable to bot traffic than clientseitig Experiments. To address this, Kameleoon uses the IAB/ABC International Spiders and Bots List to identify known bots and spiders. Kameleoon also uses the UserAgent field to filter out bots and other unwanted traffic that could otherwise skew your Konversion metrics. For more details, see the help Artikel on bot filtering.
If you use intern bots, we suggest that you pass the Wert curl/8.0 der userAgent to exclude them from our analytics.
A Besucher can only have one UserAgent. Adding a second UserAgent overwrites the first one.
| Name | Typ | Beschreibung |
|---|
| Wert (required) | string | Wert wird verwendet für comparison |
Server-side Experiments are more vulnerable to bot traffic than clientseitig Experiments. To address this, Kameleoon uses the IAB/ABC International Spiders and Bots List to identify known bots and spiders. We recommend that you pass the Benutzer agent to be filtered by Kameleoon when running serverseitig Experiments for each Besucher browsing your website, to avoid counting bots in your analytics.If you use intern bots, we suggest that you pass the Wert curl/8.0 der userAgent to exclude them from our analytics.
import { useEffect, useCallback } from 'react';
import { useInitialize, useData, UserAgent } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Add new user agent data to client
const userAgent = new UserAgent('my_unique_value');
addData('my_visitor_code', userAgent);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize, useData, UserAgent } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async () => {
await initialize();
// -- Add new user agent data to client
const userAgent = new UserAgent('my_unique_value');
addData('my_visitor_code', userAgent);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
ApplicationVersion
ApplicationVersion represents the semantic version Anzahl 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 field must follow semantic versioning. Accepted Formate are major, major.minor, oder major.minor.patch. |
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useData,
ApplicationVersion,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Add new application version data to client
const applicationVersion = new ApplicationVersion('1.2');
addData('my_visitor_code', applicationVersion);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useData,
ApplicationVersion,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { addData } = useData();
const init = useCallback(async () => {
await initialize();
// -- Add new application version data to client
const applicationVersion = new ApplicationVersion('1.2');
addData('my_visitor_code', applicationVersion);
}, [initialize, addData]);
useEffect(() => {
init();
}, [init]);
}
Rückgabetypen
DataFile
The DataFile contains das SDK Konfiguration details.
It kann extended with additional Informationen if erforderlich by clients. If you need more details, please contact your Customer Success Manager.
| Name | Typ | Beschreibung |
|---|
| featureFlags | Map<string, FeatureFlag> | A map of FeatureFlag Objekte, keyed by feature flag keys. |
| dateModified | number | The timestamp (in milliseconds) indicating when the DataFile was last modified. |
import { FeatureFlag } from '@kameleoon/javascript-sdk';
// Retrieves the map of feature flags from the DataFile.
// The map is keyed by feature flag identifiers, with each value being a FeatureFlag object.
const featureFlags: Map<string, FeatureFlag> = dataFile.featureFlags;
// Retrieves the last modification timestamp of the DataFile.
// The value is a number representing milliseconds since the Unix epoch.
const dateModified: number = dateFile.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 = dateFile.dateModified;
FeatureFlag
The FeatureFlag represents a set of properties that define a feature flag itself — zum Beispiel, its Variations, Rules, Umgebung status, and other related details.
It kann extended with additional Informationen if erforderlich by clients. If you need more details, please contact your Customer Success Manager.
| Name | Typ | Beschreibung |
|---|
| environmentEnabled | boolean | Indicating whether the feature flag is enabled im aktuell Umgebung. |
| defaultVariationKey | string | The key der Standard Variation associated mit dem feature flag. |
| Variationen | Map<string, Variation> | A map of Variation Objekte, keyed by Variation keys. |
| rules | Rule[] | A list of Rule Objekte |
import { Variation, Rule } from '@kameleoon/react-sdk';
// Check whether the feature flag is enabled in the current environment
const isEnvironmentEnabled: boolean = featureFlag.environmentEnabled;
// Retrieve the key of the default variation
const defaultVariationKey: string = featureFlag.defaultVariationKey;
// Retrieve all variations of the feature flag as a map (key = variation key, value = Variation object)
const variations: Map<string, Variation> = featureFlag.variations;
// Retrieve all targeting rules associated with the feature flag
const rules: Rule[] = featureFlag.rules;
// Check whether the feature flag is enabled in the current environment
const isEnvironmentEnabled = featureFlag.environmentEnabled;
// Retrieve the key of the default variation
const defaultVariationKey = featureFlag.defaultVariationKey;
// Retrieve all variations of the feature flag as a map (key = variation key, value = Variation object)
const variations = featureFlag.variations;
// Retrieve all targeting rules associated with the feature flag
const rules = featureFlag.rules;
Rule
The Rule represents a set of properties that define a rule itself — zum Beispiel, its Variations.
It kann extended with additional Informationen if erforderlich by clients. If you need more details, please contact your Customer Success Manager.
| Name | Typ | Beschreibung |
|---|
| Variationen | Map<string, Variation> | A map of Variation Objekte, keyed by Variation keys. |
import { Variation } from '@kameleoon/react-sdk';
// Retrieve all variations of the rule as a map (key = variation key, value = Variation object)
const variations: Map<string, Variation> = rule.variations;
// Retrieve all variations of the rule as a map (key = variation key, value = Variation object)
const variations = rule.variations;
Variation
Variation contains Informationen about the assigned Variation zum Besucher (or the Standard Variation, if no specific assignment exists).
| Name | Typ | Beschreibung |
|---|
| name | string | name der Variation. |
| key | string | key der Variation. |
| id | number oder null | id der Variation oder null if the Besucher landed on the Standard Variation. |
| experimentId | number oder null | id der Experiment oder null if the Besucher landed on the Standard Variation. |
| Variablen | Map<string, Variable> | map of Variablen für den Variation, where key is the Variable key and Wert is the Variable Objekt. |
- Ensure that your code handles the case where
id oder experimentId kann null, indicating a Standard Variation.
- The
variables map könnte empty if no Variablen are associated mit dem Variation.
// Retrieving the variation name
const variationName = variation.name;
// Retrieving the variation key
const variationKey = variation.key;
// Retrieving the variation id
const variationId = variation.id;
// Retrieving the experiment id
const experimentId = variation.experimentId;
// Retrieving the variables map
const variables = variation.variables;
// Retrieving the variation name
const variationName = variation.name;
// Retrieving the variation key
const variationKey = variation.key;
// Retrieving the variation id
const variationId = variation.id;
// Retrieving the experiment id
const experimentId = variation.experimentId;
// Retrieving the variables map
const variables = variation.variables;
Variable
Variable contains Informationen about a Variable associated mit dem assigned Variation.
| Name | Typ | Beschreibung |
|---|
| key | string | The eindeutig key identifying the Variable. |
| type | string | The type der Variable. Possible Werte: BOOLEAN, NUMBER, STRING, JSON, JS, CSS. |
| Wert | any | The Wert der Variable, which kann der following types: boolean, Anzahl, String, Record<string, any>, any[]. |
// Retrieving the variables map
const variables = variation.variables;
// Variable type can be retrieved for further processing
const type = variables.get('isDiscount')?.type || '';
// Retrieving the variable value by key
const isDiscount = variables.get('isDiscount')?.value || false;
// Variable value can be of different types
const title = variables.get('title')?.value || '';
// Retrieving the variables map
const variables = variation.variables;
// Variable type can be retrieved for further processing
const type = variables.get('isDiscount')?.type || '';
// Retrieving the variable value by key
const isDiscount = variables.get('isDiscount')?.value || false;
// Variable value can be of different types
const title = variables.get('title')?.value || '';
Veraltete Methoden
These Methoden are deprecated and wird removed im next major aktualisieren.
getFeatureFlagVariationKey()
- 📨 Sendet Tracking-Daten an Kameleoon
- 🎯 Events:
EventType.Evaluation
The Methode getFeatureFlagVariationKey(), which is used mit dem useFeatureFlag Hook, retrieves the Variation key for a Besucher identified by their visitorCode. This process includes checking the Targeting criteria, identifying the appropriate Variation assigned zum Besucher, storing this Informationen, and sending a tracking Anfrage.
If a Benutzer has never been associated with a feature flag, das SDK will randomly return a Variation key according zum rules of that feature flag. If the Benutzer is already linked zum feature flag, das SDK will identify the previously assigned Variation key. If the Benutzer does not meet any der specified rules, das SDK will return the Standard Wert defined in Kameleoon’s feature flag delivery rules. It’s important to note that the Standard Wert may not always be a Variation key; it could also be a boolean Wert or another data type, depending on how the feature flag is configured.
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getFeatureFlagVariationKey } = useFeatureFlag();
const { getVisitorCode } = useVisitorCode();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code using `getVisitorCode` function.
const visitorCode = getVisitorCode();
const featureKey = 'my_feature_key';
// -- Get the variationKey for the visitor under `visitorCode` in the feature flag.
const variationKey = getFeatureFlagVariationKey(visitorCode, featureKey);
}, [initialize, visitorCode, getFeatureFlagVariationKey, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getFeatureFlagVariationKey } = useFeatureFlag();
const { getVisitorCode } = useVisitorCode();
const init = useCallback(async () => {
await initialize();
// -- Get visitor code using `getVisitorCode` function
const visitorCode = getVisitorCode();
const featureKey = 'my_feature_key';
// -- Get the variationKey for the visitor under `visitorCode` in the found feature flag
const variationKey = getFeatureFlagVariationKey(visitorCode, featureKey);
}, [initialize, visitorCode, getFeatureFlagVariationKey, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
Argumente
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | Eindeutige Besucher-Identifikationszeichenfolge, darf 255 Zeichen nicht überschreiten |
| featureKey (required) | string | ein eindeutiger Schlüssel für den feature flag |
Rückgabewert
| Typ | Beschreibung |
|---|
string | a string containing Variable key für den allocated feature flag Variation für den bereitgestellt Besucher. |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Die Methode was executed before initialize was done for kameleoonClient |
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.FeatureFlagConfigurationNotFound | Es wurde kein feature flag für den angegebenen featureKey |
KameleoonException.FeatureFlagEnvironmentDisabled | Feature flag is disabled für den aktuell Umgebung |
getVisitorFeatureFlags()
- 🚫 Doesn’t send Tracking Data to Kameleoon
- 🎯 Events:
EventType.Evaluation (for each feature flag)
The getVisitorFeatureFlags Methode, utilized mit dem useFeatureFlag Hook, returns a list of active feature flags that target the Besucher associated mit dem visitorCode (the Besucher must have one der allocated Variationen).
This Methode only collects the feature flags that are aktuell active für den Besucher. As a result, it does not include any feature flags for which the Besucher is assigned zum “off” Variation (Standard or control). If you need to retrieve all der Besucher’s feature flags, use getFeatureFlags stattdessen.Zum Beispiel:// -- `getVisitorFeatureFlags` doesn't trigger feature experiments;
// it only returns feature flags where visitors didn't get the `off` variation.
getVisitorFeatureFlags('my_visitor').forEach(({ key }) => {
// -- `getFeatureFlagVariationKey` triggers a feature experiment,
// as `off` is already filtered out - visitors will never take part
// in an experiment where the `off` variation was allocated.
getFeatureFlagVariationKey('my_visitor', key);
});
For cases where you need all der Besucher’s feature flags, use getFeatureFlags stattdessen:// -- Both `off` and other variations are processed as expected
getFeatureFlags('my_visitor').forEach(({ key }) => {
getFeatureFlagVariationKey('my_visitor', key);
});
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { getVisitorFeatureFlags } = useFeatureFlag();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Get active feature flags for visitor
const featureFlags = getVisitorFeatureFlags(visitorCode);
}, [initialize, visitorCode, getVisitorFeatureFlags, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { getVisitorFeatureFlags } = useFeatureFlag();
const init = useCallback(async () => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Get active feature flags for visitor
const featureFlags = getVisitorFeatureFlags(visitorCode);
}, [initialize, visitorCode, getVisitorFeatureFlags, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
Argumente
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | Eindeutige Besucher-Identifikationszeichenfolge, darf 255 Zeichen nicht überschreiten |
Rückgabewert
| Typ | Beschreibung |
|---|
FeatureFlagType[] | list of feature flags, each feature flag item contains id und key. |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Die Methode was executed before the kameleoonClient den Aufruf abgeschlossen hat initialize call |
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.StorageRead | Error while reading Speicher data |
getActiveFeatureFlags()
- 🚫 Doesn’t send Tracking Data to Kameleoon
- 🎯 Events:
EventType.Evaluation (for each feature flag)
The getActiveFeatureFlags Methode, collected mit dem useFeatureFlag Hook, returns a Map, where key is feature key and Wert is detailed Informationen about the Besucher’s Variation and it’s Variablen
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { getActiveFeatureFlags } = useFeatureFlag();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Get active feature flags for visitor
// with detailed variation and variables data
const activeFeatures = 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: []
// }
// }
}, [initialize, visitorCode, getVisitorFeatureFlags, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
init();
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { getActiveFeatureFlags } = useFeatureFlag();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Get active feature flags for visitor
// with detailed variation and variables data
const activeFeatures = 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: []
// }
// }
}, [initialize, visitorCode, getVisitorFeatureFlags, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
init();
This Methode only collects the Besucher’s active feature flags. This means the result excludes alle feature flags for which the Besucher is assigned zum off (Standard or control) Variation. When you need all der Besucher’s feature flags to iterate over, use getFeatureFlags stattdessen.See the getVisitorFeatureFlags CAUTION Abschnitt Methode for more details.
Argumente
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | Eindeutige Besucher-Identifikationszeichenfolge, darf 255 Zeichen nicht überschreiten |
Rückgabewert
| Typ | Beschreibung |
|---|
Map<string, KameleoonVariationType> | a map of feature flags, where key is feature key and Wert is detailed Informationen about the Besucher’s Variation and it’s Variablen |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Die Methode was executed before the kameleoonClient den Aufruf abgeschlossen hat initialize call |
KameleoonException.VisitorCodeMaxLength | The visitor code exceeded the maximum length of 255 characters |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.StorageRead | Error while reading Speicher data |
KameleoonException.NumberParse | Couldn’t parse Number Wert |
KameleoonException.JSONParse | Couldn’t parse JSON Wert |
getFeatureFlagVariable()
- 📨 Sendet Tracking-Daten an Kameleoon
- 🎯 Events:
EventType.Evaluation
The getFeatureFlagVariable Methode, collected with useFeatureFlag Hook, returns a Variable für den Besucher under visitorCode im found feature flag, this includes Targeting check, finding the according Variation exposed zum Besucher and saving it to Speicher zusammen mit sending tracking Anfrage.
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useVisitorCode,
useFeatureFlag,
VariableType,
JSONType,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { getFeatureFlagVariable } = useFeatureFlag();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Get feature variable
const result = 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;
}
}, [initialize, getFeatureFlagVariable, visitorCode, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useVisitorCode,
useFeatureFlag,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { getFeatureFlagVariable } = useFeatureFlag();
const init = useCallback(async () => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Get feature variable
const variableResult = getFeatureFlagVariable({
visitorCode,
featureKey: 'my_feature_key',
variableKey: 'my_variable_key',
});
const { type, value } = variableResult;
}, [initialize, getFeatureFlagVariable, visitorCode, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
Argumente
Parameters Objekt of type GetFeatureFlagVariableParamsType containing the following fields:
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | Eindeutige Besucher-Identifikationszeichenfolge, darf 255 Zeichen nicht überschreiten |
| featureKey (required) | string | ein eindeutiger Schlüssel für den feature flag |
| variableKey (required) | string | key der Variable to be found for a feature flag mit dem specified featureKey, kann found on Kameleoon Platform |
Rückgabewert
| Typ | Beschreibung |
|---|
FeatureFlagVariableType | a Variable Objekt containing type und value fields. You can check the type field against VariableType enum. Zum Beispiel, if the type is VariableType.BOOLEAN then value wird a boolean type. |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Die Methode was executed before initialize was done for kameleoonClient |
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.FeatureFlagConfigurationNotFound | Es wurde kein feature flag für den angegebenen featureKey |
KameleoonException.FeatureFlagVariableNotFound | No feature Variable was found für den specified visitorCode und variableKey |
KameleoonException.FeatureFlagEnvironmentDisabled | Feature flag is disabled für den aktuell Umgebung |
KameleoonException.JSONParse | Couldn’t parse JSON Wert |
KameleoonException.NumberParse | Couldn’t parse Number Wert |
getFeatureFlagVariables()
- 📨 Sendet Tracking-Daten an Kameleoon
- 🎯 Events:
EventType.Evaluation (for each feature flag)
The getFeatureFlagVariables Methode, collected mit dem useFeatureFlag, Hook returns a list of Variablen für den Besucher under visitorCode im found feature flag, this includes Targeting check, finding the according Variation exposed zum Besucher and saving it to Speicher zusammen mit sending tracking Anfrage.
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
} from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { getFeatureFlagVariables } = useFeatureFlag();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode();
// -- Get a list of variables for the visitor under `visitorCode` in the feature flag
const variables = getFeatureFlagVariables(visitorCode, 'my_feature_key');
}, [initialize, getFeatureFlagVariables, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import {
useInitialize,
useFeatureFlag,
useVisitorCode,
} from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getVisitorCode } = useVisitorCode();
const { getFeatureFlagVariables } = useFeatureFlag();
const init = useCallback(async () => {
await initialize();
// -- Get visitor code
const visitorCode = getVisitorCode('www.example.com');
// -- Get a list of variables for the visitor under `visitorCode` in the feature flag
const variables = getFeatureFlagVariables(visitorCode, 'my_feature_key');
}, [initialize, getFeatureFlagVariables, getVisitorCode]);
useEffect(() => {
init();
}, [init]);
}
Argumente
| Name | Typ | Beschreibung |
|---|
| visitorCode (required) | string | Eindeutige Besucher-Identifikationszeichenfolge, darf 255 Zeichen nicht überschreiten |
| featureKey (required) | string | ein eindeutiger Schlüssel für den feature flag |
Rückgabewert
| Typ | Beschreibung |
|---|
FeatureVariableResultType[] | a list of Variable Objekte containing key, type und value fields. You can check the type field against VariableType enum. Zum Beispiel, if the type is VariableType.BOOLEAN then value wird a boolean type. |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Die Methode was executed before the kameleoonClient den Aufruf abgeschlossen hat initialize call |
KameleoonException.VisitorCodeMaxLength | Der Visitor-Code hat die maximale Länge (255 Zeichen) überschritten |
KameleoonException.VisitorCodeEmpty | The visitor code is empty |
KameleoonException.FeatureFlagConfigurationNotFound | Es wurde kein feature flag für den angegebenen featureKey |
KameleoonException.FeatureFlagVariationNotFound | No feature Variation was found für den specified visitorCode und variableKey |
KameleoonException.FeatureFlagEnvironmentDisabled | Feature flag is disabled für den aktuell Umgebung |
KameleoonException.JSONParse | Couldn’t parse JSON Wert |
KameleoonException.NumberParse | Couldn’t parse Number Wert |
onConfigurationUpdate()
Verwenden Sie die onEvent Methode with EventType.ConfigurationUpdate stattdessen.
Die Methode onConfigurationUpdate collected with useInitialize Hook fires a Callback on client Konfiguration aktualisieren.
This Hook only works for server sent events of real time aktualisieren
import { useEffect, useCallback } from 'react';
import { useInitialize } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize, onConfigurationUpdate } = useInitialize();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Define logic to execute on client configuration update
onConfigurationUpdate(() => {
// -- My Logic
});
}, [initialize, onConfigurationUpdate]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize, onConfigurationUpdate } = useInitialize();
const init = useCallback(async () => {
await initialize();
// -- Define logic to execute on client configuration update
onConfigurationUpdate(() => {
// -- My Logic
});
}, [initialize, onConfigurationUpdate]);
useEffect(() => {
init();
}, [init]);
}
Argumente
| Name | Typ | Beschreibung |
|---|
| Callback (required) | () => void | Callback Funktion with no Parameter that wird called upon Konfiguration aktualisieren |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Die Methode was executed before the kameleoonClient completed its initialize call |
getFeatureFlags()
🚫 Doesn’t send Tracking Data to Kameleoon
The getFeatureFlags Methode collected mit dem useFeatureFlag Hook returns a list of feature flags stored im client Konfiguration.
import { useEffect, useCallback } from 'react';
import { useInitialize, useFeatureFlag } from '@kameleoon/react-sdk';
function MyComponent(): JSX.Element {
const { initialize } = useInitialize();
const { getFeatureFlags } = useFeatureFlag();
const init = useCallback(async (): Promise<void> => {
await initialize();
// -- Get list of all feature flags
const featureFlags = getFeatureFlags();
}, [initialize, getFeatureFlags]);
useEffect(() => {
init();
}, [init]);
}
import { useEffect, useCallback } from 'react';
import { useInitialize, useFeatureFlag } from '@kameleoon/react-sdk';
function MyComponent() {
const { initialize } = useInitialize();
const { getFeatureFlags } = useFeatureFlag();
const init = useCallback(async () => {
await initialize();
// -- Get list of all feature flags
const featureFlags = getFeatureFlags();
}, [initialize, getFeatureFlags]);
useEffect(() => {
init();
}, [init]);
}
Rückgabewert
| Typ | Beschreibung |
|---|
FeatureFlagType[] | list of feature flags, each feature flag item contains id und key. |
Geworfene Ausnahmen
| Typ | Beschreibung |
|---|
KameleoonException.Initialization | Die Methode was executed before the kameleoonClient den Aufruf abgeschlossen hat initialize call |