### Install JavaScript SDK via npm Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Use this command to install the A/B Smartly JavaScript SDK using npm. ```shell npm install @absmartly/javascript-sdk --save ``` -------------------------------- ### Create Context with Refresh Period Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Configure a context to periodically refresh experiment data, useful for long-running SPAs to pick up newly started experiments. The refresh period is set in milliseconds. ```javascript const request = { units: { session_id: '5ebf06d8cb5d8137290c4abb64155584fbdb64d8', }, }; const context = sdk.createContext(request, { refreshPeriod: 5 * 60 * 1000 }); ``` -------------------------------- ### Manually Refresh Context Data Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Call the `refresh()` method to pull updated experiment data from the collector. This ensures that recently started experiments can be triggered on subsequent `treatment()` calls. ```javascript setTimeout(async () => { try { context.refresh(); } catch(error) { console.error(error); } }, 5 * 60 * 1000); ``` -------------------------------- ### Initialize SDK with Basic Configuration Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Initialize the SDK with endpoint, API key, environment, and application name. Ensure environment variables are set. ```javascript // somewhere in your application initialization code const sdk = new absmartly.SDK({ endpoint: 'https://sandbox.absmartly.io/v1', apiKey: process.env.ABSMARTLY_API_KEY, environment: process.env.NODE_ENV, application: process.env.APPLICATION_NAME, }); ``` -------------------------------- ### Initialize SDK with Application Name and Version Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Configure the SDK with an application object that includes both name and version for event tracking. ```javascript const sdk = new absmartly.SDK({ endpoint: 'https://sandbox.absmartly.io/v1', apiKey: process.env.ABSMARTLY_API_KEY, environment: process.env.NODE_ENV, application: { name: 'website', version: '1.2.3' }, }); ``` -------------------------------- ### Build All SDK Formats Source: https://github.com/absmartly/javascript-sdk/blob/main/CONTRIBUTING.md Run this command to generate all SDK builds: UMD for browsers, ES2015 modules, and CommonJS modules. ```bash npm run build ``` -------------------------------- ### Create Context with Async/Await Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Create a new A/B Smartly context and use async/await syntax to handle the context readiness and potential errors. ```javascript // define a new context request const request = { units: { session_id: '5ebf06d8cb5d8137290c4abb64155584fbdb64d8', }, }; // create context with raw promises const context = sdk.createContext(request); try { await context.ready(); console.log("ABSmartly Context ready!") } catch (error) { console.log(error); } ``` -------------------------------- ### Include SDK Directly in Browser Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Include the optimized A/B Smartly SDK directly in your HTML head section using unpkg.com. ```html ``` -------------------------------- ### Initialize Context with Server-Side Data Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Initialize an A/B Smartly context on the client-side using pre-fetched data from the server to avoid an extra round-trip. ```html
``` -------------------------------- ### Create Context with Raw Promises Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Create a new A/B Smartly context using a request object and handle the ready state with promises. ```javascript // define a new context request const request = { units: { session_id: '5ebf06d8cb5d8137290c4abb64155584fbdb64d8', }, }; // create context with raw promises const context = sdk.createContext(request); context.ready().then((response) => { console.log("ABSmartly Context ready!") }).catch((error) => { console.log(error); }); ``` -------------------------------- ### Run All Tests Source: https://github.com/absmartly/javascript-sdk/blob/main/CONTRIBUTING.md Execute this command to run all unit tests for both browser and Node.js environments. ```bash npm run test ``` -------------------------------- ### Instantiate SDK with Custom Event Logger Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Configure the SDK with a custom event logger during instantiation. This logger can handle events like errors, context readiness, refreshes, publishes, exposures, goals, and finalization. ```javascript const sdk = new absmartly.SDK({ endpoint: 'https://sandbox-api.absmartly.com/v1', apiKey: process.env.ABSMARTLY_API_KEY, environment: process.env.NODE_ENV, application: process.env.APPLICATION_NAME, eventLogger: (context, eventName, data) => { if (eventName == "error") { console.error(data); } }, }); ``` -------------------------------- ### Import JavaScript SDK Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Import the SDK into your JavaScript application using require or ES6 modules. ```javascript const absmartly = require('@absmartly/javascript-sdk'); // OR with ES6 modules: import absmartly from '@absmartly/javascript-sdk'; ``` -------------------------------- ### Run Linter Source: https://github.com/absmartly/javascript-sdk/blob/main/CONTRIBUTING.md Execute this command to run the linter and fix any identified code style issues before pushing changes. ```bash npm run lint ``` -------------------------------- ### Include System Attributes in Context Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Enable automatic inclusion of system attributes like SDK name and version in publish payloads by setting `includeSystemAttributes` to `true` when creating a context. ```javascript const context = sdk.createContext(request, { includeSystemAttributes: true, }); ``` -------------------------------- ### Set Multiple Context Attributes Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Set multiple attributes for the context at once using the `attributes()` method. This can be called before the context is ready. ```javascript context.attributes({ customer_age: 'new_customer', }); ``` -------------------------------- ### Add Multiple Units to Context Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Add multiple unit types to an existing context simultaneously using the `units()` method. This must be called before the context is ready and cannot override existing units. ```javascript // or context.units({ db_user_id: 1000013, }); ``` -------------------------------- ### Peek at Treatment Variants Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Use the `peek()` method to check a treatment variant without triggering an exposure. This is useful for conditional logic based on experiment assignment. ```javascript if (context.peek("exp_test_experiment") == 0) { // user is in control group (variant 0) } else { // user is in treatment group } ``` -------------------------------- ### Publish Pending Data Before Navigation Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Ensure all queued events are sent to the A/B Smartly collector before a user navigates away. This method returns a promise. ```javascript await context.publish().then(() => { window.location = "https://www.absmartly.com" }) ``` -------------------------------- ### Finalize Context and Publish Data Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Publish all pending events and seal the context to prevent further event generation. This method returns a promise. ```javascript await context.finalize().then(() => { window.location = "https://www.absmartly.com" }) ``` -------------------------------- ### Add Single Unit to Context Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Add a new unit type to an existing context using the `unit()` method. This must be called before the context is ready and cannot override existing units. ```javascript context.unit('db_user_id', 1000013); ``` -------------------------------- ### Track Goal Achievement Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Record a goal achievement with associated event data. Goals must be pre-defined in the A/B Smartly web console. ```javascript context.track("payment", { item_count: 1, total_amount: 1999.99 }); ``` -------------------------------- ### Set Single Context Attribute Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Set a single attribute for the context using the `attribute()` method. This can be called before the context is ready. ```javascript context.attribute('user_agent', navigator.userAgent); ``` -------------------------------- ### Select Treatment for an Experiment Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Check which treatment variant a user is assigned to for a given experiment. Returns 0 for the control group. ```javascript if (context.treament("exp_test_experiment") == 0) { // user is in control group (variant 0) } else { // user is in treatment group } ``` -------------------------------- ### Set HTTP Request Timeout Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Set a custom timeout for an individual HTTP request, such as `createContext`, overriding the global SDK timeout. The timeout is specified in milliseconds. ```javascript const context = sdk.createContext(request, { refreshPeriod: 5 * 60 * 1000 }, { timeout: 1500 }); ``` -------------------------------- ### Cancel HTTP Request with AbortSignal Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Cancel an inflight HTTP request using an `AbortSignal`. This is useful for scenarios like user navigation away from a page. A timeout is used to demonstrate cancellation. ```javascript const controller = new absmartly.AbortController(); const context = sdk.createContext(request, { refreshPeriod: 5 * 60 * 1000 }, { signal: controller.signal }); // abort request if not ready after 1500ms const timeoutId = setTimeout(() => controller.abort(), 1500); await context.ready(); clearTimeout(timeoutId); ``` -------------------------------- ### Override Treatment Variants Source: https://github.com/absmartly/javascript-sdk/blob/main/README.md Force a specific treatment variant for an experiment using `override()` or `overrides()`. These methods can be called before the context is ready. ```javascript context.override("exp_test_experiment", 1); // force variant 1 of treatment context.overrides({ exp_test_experiment: 1, exp_another_experiment: 0, }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.