### Initialize Sensors Data Web JS SDK and A/B Testing Plugin
Source: https://context7.com/sensorsdata/abtesting-sdk-web/llms.txt
Includes importing the necessary SDKs and plugins, initializing the main JS SDK, and then registering and initializing the A/B Testing plugin with various configuration options for experiments.
```html
```
--------------------------------
### Initialize Multilink Experiment
Source: https://context7.com/sensorsdata/abtesting-sdk-web/llms.txt
Initializes the A/B Testing SDK with multilink experiment configurations. Supports custom redirect behavior via `onRedirect` hook. Ensure the SDK is loaded before the `init` call.
```javascript
abtest.init(sa, {
url: 'https://abtesting.example.com/api/v2/abtest/online/results?project-key=YOUR_KEY',
multilink: {
timeout: 500,
use_mask: true,
pass_params: true,
// 自定义跳转行为(可选,默认直接修改 location.href)
onRedirect: function (targetUrl) {
console.log('即将跳转至试验组 URL:', targetUrl);
// 可在此处加入埋点或动画后再跳转
setTimeout(function () {
location.href = targetUrl;
}, 100);
}
},
visualize: false
});
// URL 参数说明:
// 对照组:https://example.com/product?id=123
// 试验组:https://example.com/product-v2?id=123
// 命中后 SDK 自动处理跳转,pass_params=true 时保留 ?id=123 参数
```
--------------------------------
### Initialize Visual A/B Test
Source: https://context7.com/sensorsdata/abtesting-sdk-web/llms.txt
Initializes the A/B Testing SDK to enable visual A/B tests. Requires `enable_visualize: true` to activate. The SDK uses `MutationObserver` to apply changes and supports SPA route transitions.
```javascript
abtest.init(sa, {
url: 'https://abtesting.example.com/api/v2/abtest/online/results?project-key=YOUR_KEY',
multilink: false,
visualize: {
// 必须显式设置为 true 才能开启可视化试验
enable_visualize: true,
// 遮罩超时时间(ms),超时后自动移除遮罩恢复页面
timeout: 500,
// 是否开启遮罩层防止闪烁
use_mask: true,
// 自定义可视化试验 vabtest.min.js 的加载地址(可选)
vabtest_url: 'https://static.sensorsdata.cn/sdk/plugin/vabtest/0.1.4/vabtest.min.js'
}
});
// 可视化试验配置示例(在神策平台配置,SDK 自动执行):
// {
// "experiment_type": "VISUAL",
// "control_link": "https://example.com/home",
// "link_match_type": "FUZZY",
// "experiment_value": [
// {
// "selector": "body > div:nth-of-type(1) > h1:nth-of-type(1)",
// "tagName": "h1",
// "props": {
// "text": "新版标题文案",
// "attributes": {
// "style": { "color": "#ff4d4f", "fontSize": "24px" }
// }
// }
// }
// ]
// }
```
--------------------------------
### SDK Initialization
Source: https://context7.com/sensorsdata/abtesting-sdk-web/llms.txt
Initializes the A/B Testing plugin after the Sensors Web JS SDK is ready. It requires the SDK instance and configuration parameters, including settings for multi-link and visual experiments.
```APIDOC
## SDK Initialization `init(sd, para)`
### Description
Initializes the A/B Testing plugin after the Sensors Web JS SDK is ready. It requires the SDK instance and configuration parameters, including settings for multi-link and visual experiments.
### Parameters
- **sd** (object) - The initialized Sensors Web JS SDK instance.
- **para** (object) - Configuration object for the A/B Testing plugin.
- **url** (string) - The URL for the A/B Testing service (must include project-key).
- **timeout_milliseconds** (number) - Request timeout in milliseconds (default: 3000).
- **update_interval** (number) - Local cache update interval in milliseconds (default: 600000).
- **collect_bridge_status** (boolean) - Whether to report bridge status properties (default: true).
- **encrypt_cookie** (boolean) - Whether to encrypt local cache (default: false).
- **multilink** (object, optional) - Configuration for multi-link experiments.
- **timeout** (number) - Maximum time to wait for split test results (ms).
- **use_mask** (boolean) - Whether to display a white screen mask to prevent page flicker.
- **pass_params** (boolean) - Whether to pass original URL parameters to the target link.
- **control_link_search** (string) - Control group URL parameter processing strategy.
- **experiment_link_search** (string) - Experiment group URL parameter processing strategy.
- **visualize** (object, optional) - Configuration for visual experiments.
- **enable_visualize** (boolean) - Enable visual experiments.
- **timeout** (number) - Timeout for visual experiment requests (ms).
- **use_mask** (boolean) - Whether to display a white screen mask.
```
--------------------------------
### fastFetchABTest
Source: https://context7.com/sensorsdata/abtesting-sdk-web/llms.txt
Prioritizes reading from local cache, and if the cache is missed, it requests the server. This method offers a balance between performance and real-time data, making it the most commonly used for code experiments.
```APIDOC
## `fastFetchABTest(para)`
### Description
Prioritizes reading from local cache (localStorage), and if the cache is missed, it requests the server. This method offers a balance between performance and real-time data, making it the most commonly used for code experiments.
### Parameters
- **para** (object)
- **param_name** (string) - The name of the experiment parameter.
- **value_type** (string) - The expected data type of the returned value ('String', 'Number', 'Boolean', 'Object').
- **default_value** (any) - The default value if the experiment is not hit or the request fails. Must match `value_type`.
- **timeout_milliseconds** (number, optional) - Request timeout in milliseconds.
- **properties** (object, optional) - Custom properties for fine-grained user segmentation.
- **callback** (function) - Required. A callback function that receives the experiment result.
```
--------------------------------
### Initialize for App H5 JSBridge Mode
Source: https://context7.com/sensorsdata/abtesting-sdk-web/llms.txt
Initializes the A/B Testing SDK for App H5 environments. The SDK automatically detects and uses JSBridge if available, falling back to HTTP mode otherwise. `collect_bridge_status` enables reporting of bridge status in events.
```javascript
// H5 场景下 init 配置与 Web 一致,SDK 自动切换通道
abtest.init(sa, {
// H5 场景下 url 字段非必须(Bridge 模式不需要),但保留也不影响
url: 'https://abtesting.example.com/api/v2/abtest/online/results?project-key=YOUR_KEY',
timeout_milliseconds: 3000,
collect_bridge_status: true, // 开启后触发事件携带 $sdk_bridge_status
multilink: false,
visualize: false
});
// SDK 内部 bridgeState 可能值:
// 'ab_bridge_ok' — Bridge 连接成功,通过 App 获取分流
// 'ab_no_host_bridge' — 无 App Bridge,使用 HTTP 模式(Web 环境)
// 'ab_no_abtest_bridge' — App Bridge 存在但不支持 A/B 模块
// 调用方式与 Web 端完全一致
abtest.fastFetchABTest({
param_name: 'app_h5_banner',
value_type: 'String',
default_value: 'default_banner',
callback: function (value) {
renderBanner(value);
}
});
```
--------------------------------
### Fetch AB Test Variable with Cache Priority
Source: https://context7.com/sensorsdata/abtesting-sdk-web/llms.txt
The `fastFetchABTest` interface is recommended for most code experiment scenarios as it prioritizes local cache lookup before making a network request. It balances performance and real-time needs.
```javascript
abtest.fastFetchABTest({
param_name: 'checkout_button_color',
value_type: 'String',
default_value: '#1890ff',
timeout_milliseconds: 1500,
// 用于精细化分组的自定义属性
properties: {
is_new_user: true
},
callback: function (color) {
var btn = document.getElementById('checkout-btn');
if (btn) {
btn.style.backgroundColor = color;
console.log('按钮颜色试验值:', color);
}
}
});
// Object 类型示例
abtest.fastFetchABTest({
param_name: 'recommend_algo_config',
value_type: 'Object',
default_value: { strategy: 'default', limit: 10 },
callback: function (config) {
console.log('推荐算法配置:', config.strategy, '条目数量:', config.limit);
loadRecommendations(config);
}
});
```
--------------------------------
### asyncFetchABTest
Source: https://context7.com/sensorsdata/abtesting-sdk-web/llms.txt
Fetches experiment variables from the server in real-time with each call. This method is suitable for scenarios requiring strong real-time data.
```APIDOC
## `asyncFetchABTest(para)`
### Description
Fetches experiment variables from the server in real-time with each call. This method is suitable for scenarios requiring strong real-time data. The `callback` function receives the experiment result.
### Parameters
- **para** (object)
- **param_name** (string) - The name of the experiment parameter configured on the Sensors A/B Testing platform.
- **value_type** (string) - The expected data type of the returned value. Supported types: 'String', 'Number', 'Boolean', 'Object'.
- **default_value** (any) - The default value to use if the experiment is not hit or the request fails. Must match `value_type`.
- **timeout_milliseconds** (number, optional) - Request timeout in milliseconds. If not set, the global configuration is used.
- **custom_properties** (object, optional) - Custom properties for user segmentation.
- **callback** (function) - Required. A callback function that receives the experiment result.
```
--------------------------------
### Fetch AB Test Variable from Cache Only (Synchronous)
Source: https://context7.com/sensorsdata/abtesting-sdk-web/llms.txt
Use `fetchCacheABTest` for synchronous retrieval of experiment variables directly from memory or localStorage cache. This method does not initiate any network requests and is suitable for critical rendering paths.
```javascript
// 同步读取缓存中的试验变量
var fontSize = abtest.fetchCacheABTest({
param_name: 'article_font_size',
value_type: 'Number',
default_value: 14
});
// 直接使用返回值(无 callback)
console.log('当前字号:', fontSize);
document.body.style.fontSize = fontSize + 'px';
// Boolean 类型示例
var showNewFeature = abtest.fetchCacheABTest({
param_name: 'enable_new_editor',
value_type: 'Boolean',
default_value: false
});
if (showNewFeature) {
loadNewEditor();
} else {
loadLegacyEditor();
}
```
--------------------------------
### Fetch AB Test Variable with Real-time Request
Source: https://context7.com/sensorsdata/abtesting-sdk-web/llms.txt
Use `asyncFetchABTest` for scenarios requiring strong real-time data. It makes a network request on each call and returns results via a callback. Ensure `default_value` matches `value_type`.
```javascript
abtest.asyncFetchABTest({
// 试验参数名(在神策 A/B Testing 平台配置)
param_name: 'home_banner_title',
// 期望返回的值类型
value_type: 'String',
// 若未命中试验或请求失败时的默认值
default_value: '默认标题',
// 请求超时时间(ms),可选,未设置则使用全局配置
timeout_milliseconds: 2000,
// 自定义属性(用于定向人群分组),可选
custom_properties: {
user_level: 'vip',
city: 'beijing'
},
// 必填:接收试验结果的回调
callback: function (result) {
if (typeof result === 'string') {
document.getElementById('banner-title').innerText = result;
console.log('命中试验,变量值:', result);
} else {
console.log('未命中试验,使用默认值:', result);
}
}
});
```
--------------------------------
### fetchCacheABTest
Source: https://context7.com/sensorsdata/abtesting-sdk-web/llms.txt
Synchronously reads only from local cache (memory/localStorage) without making any network requests. This is suitable for retrieving cached experiment variables critical for page rendering.
```APIDOC
## `fetchCacheABTest(para)`
### Description
Synchronously reads only from local cache (memory/localStorage) without making any network requests. This is suitable for retrieving cached experiment variables critical for page rendering.
### Parameters
- **para** (object)
- **param_name** (string) - The name of the experiment parameter.
- **value_type** (string) - The expected data type of the returned value ('String', 'Number', 'Boolean', 'Object').
- **default_value** (any) - The default value if the experiment is not found in cache. Must match `value_type`.
### Returns
- (any) The experiment variable value from the cache, or the `default_value` if not found.
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.