Skip to content

JavaScript SDK

Getting Started

This document will guide you on how to get started with ABetterChoice for web applications in JavaScript.

If you haven't already, please follow this guide to create an ABetterChoice project and set up some experiments. While you can choose to skip this step for now, please be aware that you may need the project ID and the names of the experiment layers in the following sections.

Installation

  1. Import SDK: Use tnpm to import from the internal local repository (temporarily hosted in the internal repository):
groovy
$ tnpm install @tencent/abc_web_sdk
  1. Integrate via import script:
groovy
....
<script src="https://res.ab.qq.com/abc/1.0.0/abc_websdk.min.js"></script>
....

SDK Initialization

After importing, we need to initialize the SDK. The numerical project ID is required for this step. You can find the project ID next to the project name in the projects dropdown menu. Screenshot 2024-05-09 at 10.07.10.png

javascript
....
// Set the log level. default disable logging, If you need to enable logging, set the level as 0.
abc.setLogLevel(0);
// Initialization can only be done once.
abc.init(
  {
    projectId: PROJECT_ID, // Required. This is the project ID of your ABC project.
    unitId: UNIT_ID, // Required. This is the User Identity ID, used for traffic splitting.
    secretKey: "API_SECRET_KEY", // Required for authentication.
    enableAutomaticPoll: true, // Optional. Default value is true. When set as true, the experiment and feature flag data will be polled and updated every 10 minutes.
    enableAutomaticExposure: false, // Optional. Default value is false. When set as true, the exposure data will automatically be logged when online retrieval APIs are called.
  }).then((initResult) => {
  console.log(`ABC SDK initialization result: ${initResult}`);
});
....

Now our SDK is initialized and you can access the experiments and feature flags under the project that you just initialized. If you need to use the experiments and feature flags under another project, we also provide an API to create an instance under the new project. You will need to initialize this new instance before using it.

javascript
....
// Create a new instance for the new project.
const anotherProject = abc.getNewProject(ANOTHER_PROJECT_ID);
// Initialize this new project instance as we did above.
anotherProject.init({
  projectId: ANOTHER_PROJECT_ID, // Required. This is the project ID of your ABC project.
  unitId: UNIT_ID, // Required. This is the User Identity ID, used for traffic splitting.
  secretKey: "API_SECRET_KEY", // Required for authentication.
	...
});
....

Fetching Experiments and Logging Exposures

In this section, we will guide you on how to create a new experiment and fetch the experiment assignments using our experiment fetching APIs provided by our SDK. Some common terminologies are listed below.

TermsMeaning
UnitIDA unit ID can be a user ID, a session ID, or a machine ID. The ABC SDK assigns a unit ID to the same group consistently.
LayerA layer usually represents 100% of the units that you can run an experiment on in your product. It can be further split into one or more experiments. The traffic of the experiments under the same layer is mutually exclusive.
ExperimentAn experiment can take up to 100% of the layer traffic. It will further contain two or more experiment groups.
GroupUnits within one experiment will be split into two or more groups, e.g., control and treatment. They will be compared against each other.
ParameterThese are the values bound to a particular layer. Experiments under the same layer can share the same parameters with each other.

1. Creating a New Experiment

If you haven't done so, please go to the console and create a new experiment following our guide on how to create an experiment.

2. Fetching Experiment Assignments

Assume in step 1 we already created an experiment whose layer name is abc_layer_name. Under this layer, there is a parameter whose name is should_show_banner and type is Boolean. Note that if you use our basic version, the layer name is the same as the experiment name by default. But if you create new experiments under the same layer, you need to find the layer name under the experiment page.

The standard way of fetching the splitting results is getting the experiment assignment by the layer key, and fetching the parameters under the layer via the strong type APIs under the experiment object. Note there are two input parameters for the getExperiment API. The first one is the layer name, and the second one controls whether we enable automatic exposure logging for this API. This second parameter has a higher priority compared with the global enableAutomaticExposure parameter.

javascript
const experiment = abc.getExperiment("abc_layer_name", true);
const shouldShowBanner = experiment.getBoolValue("should_show_banner", true);

This is convenient when you have more than one parameter under the layer/experiment, and this same API will automatically give you the correct result when there are multiple experiments under the same layer, since the unit will and can only fall into one of them. One more benefit of doing this is you can iterate the experiments quickly, by deallocating the old experiment and creating new ones under the same layer without modifying the code. See more details in how to utilize parameters to run experiments

3. Logging Exposure Data

When fetching the experiment assignments above, you can choose to disable exposure logging to prevent exposure dilution. You can log the exposure manually later at the right place:

javascript
abc.logExperimentExposure(experiment);

4. Account Switching

In the case when you need to fetch the experiments for another unit id, we also support you to switch accounts via the API listed below:

javascript
abc.switchUnitId(otherUnitID: string): Promise<boolean>;

5. Forcing Data Refresh

The ABC SDK will fetch experiment results and store them locally in the client cache during the startup of your client application. In the initialization function, you can also set the enableAutomaticPoll parameter so these data can be updated every 10 minutes. But in the case when you need to force a cache refresh for these data, we also provide an API to support this use case:

javascript
abc.refreshExperiment(): Promise<boolean>

Getting Feature Flags

In this section, we will guide you through the process of retrieving the value of a feature flag. If you haven't already done so, please first follow our documentation to create one. Assuming we have already created a new feature flag named new_feature_flag , and its value type is Boolean, default its value is false, we can fetch the value in the following manner:

javascript
const featureFlagInfo = abc.getFeatureFlag("new_feature_flag");
const boolValue = featureFlagInfo.getBoolValue(false);

Complete Code Example

  1. Initialize the SDK
javascript
....
// Set the log level. If you need to enable logging, set the level as 0.
abc.setLogLevel(0);
// Initialization can only be done once.
abc.init(
  {
    projectId: PROJECT_ID, // Required. This is the project ID of your ABC project.
    unitId: UNIT_ID, // Required. This is the User Identity ID, used for traffic splitting.
    secretKey: "API_SECRET_KEY", // Required for authentication.
    enableAutomaticPoll: true, // Optional. Default value is true. When set as true, the experiment and feature flag data will be polled and updated every 10 minutes.
    enableAutomaticExposure: false, // Optional. Default value is false. When set as true, the exposure data will automatically be logged when online retrieval APIs are called.
  }).then((initResult) => {
  console.log(`ABC SDK initialization result: ${initResult}`);
});
....
  1. Use the SDK
javascript
....
/*-————————————————————————Get Experiment Information————————————————————————————————*/
// Interface to get experiment information
const experiment = abc.getExperiment("abc_layer_name", true);
if (experiment === undefined) {
	// This indicates that something wrong happened.
	handleView('There is something wrong with fetching experiments');
	return;
}
// Now you can get the parameter and use these parameters directly in your code.
const shouldShowBanner = experiment.getBoolValue("should_show_banner", true);

/*-————————————————————————Get FeatureFlag Information————————————————————————————————*/
// you can get featureFlag value by parameter key to use in your code.
const featureFlagInfo = abc.getFeatureFlag("new_feature_flag");
const boolValue = featureFlagInfo.getBoolValue(false);

/*-——————————————————-———-----——Account Switching—————————————————--———————————————*/
// Switching Account
abc.switchUnitId('other_unitId');

/*-———————————————————-----—————Forced Refresh——————————————————————--——————————*/
// Will force a request to backend and trigger cache refresh
abc.refreshExperiment();

/*-———————————————————Manually logging Experiment Exposures————————————————-———--————————*/
// When the enableAutomaticExposure is not set, you can choose to manually log exposures
abc.logExperimentExposure(experiment);

/*-———————————————————If you want to fetch experiments from a different project——————————————————————--——————————*/
// Create a new instance for the new project.
const anotherProject = abc.getNewProject(ANOTHER_PROJECT_ID);
// Initialize this new project instance as we did above.
anotherProject.init({
	projectId: ANOTHER_PROJECT_ID, // Required. This is the project ID of your new project.
	unitId: UNIT_ID, // Required. This is the User Identity ID, used for traffic splitting.
    secretKey: "API_SECRET_KEY", // Required for authentication.
	...
});
// Get experiments under the new project.
const newExperiment = anotherProject.getExperiment("another_layer_name", true);
// Now you can get the parameters as we did above.
....