@sensorswave/js-sdk
v0.9.2
Published
Sensors Wave JS SDK for web analytics
Readme
SensorsWave JS SDK
SensorsWave JS SDK is a web analytics tracking library. If you're new to SensorWave, check out our product and create an account at sensorswave.com.
SDK Usage
1. Install via npm
npm install @sensorswave/js-sdk2. Import as ES Module
import SensorsWave from '@sensorswave/js-sdk';
SensorsWave.init('your-source-token', {
debug: false,
apiHost: 'https://your-api-host.com',
autoCapture: true
});3. Import via Script Tag
<script src="/path/to/index.js"></script>
<script>
SensorsWave.init('your-source-token', {
debug: false,
apiHost: 'https://your-api-host.com',
autoCapture: true
});
</script>4. Send Custom Events
SensorsWave.trackEvent('ButtonClick', {
button_name: 'submit',
page: 'home'
});Configuration Options
| Option | Type | Default | Description | |--------|------|---------|-------------| | debug | boolean | false | Whether to enable debug mode for logging | | apiHost | string | '' | API host address for sending events | | autoCapture | boolean | true | Whether to automatically capture page events (page view, page load, page leave) | | enableClickTrack | boolean | false | Whether to enable automatic click tracking on all elements | | isSinglePageApp | boolean | false | Whether the application is a Single Page Application (enables automatic route change tracking) | | crossSubdomainCookie | boolean | true | Whether to share cookies across subdomains | | enableAB | boolean | false | Whether to enable A/B testing feature | | abRefreshInterval | number | 600000 (10 minutes) | The interval in milliseconds for refreshing A/B test configuration | | batchSend | boolean | true | Whether to use batch sending (sends events in batches up to 10 events every 5 seconds) |
API Methods
Event Tracking
trackEvent
Manually track a custom event with properties.
Parameters:
eventName(string, required): The name of the event to trackproperties(Object, optional): Additional properties to include with the event
Example:
SensorsWave.trackEvent('ButtonClick', {
button_name: 'submit',
page: 'home',
category: 'user_action'
});track
Track an event with full control over the event structure. This is an advanced method that allows you to specify all event fields manually.
Parameters:
event(AdvanceEvent, required): Complete event object with the following structure:event(string, required): Event nameproperties(Record<string, any>, optional): Event propertiestime(number, required): Timestamp in millisecondsanon_id(string, optional): Anonymous user IDlogin_id(string, optional): Logged-in user ID。At least one of the login_id and anon_id should be passed. When passed simultaneously, the login_id should be used preferentiallytrace_id(string, required): Trace ID for request trackinguser_properties(Record<string, any>, optional): User properties
Example:
SensorsWave.track({
event: 'PurchaseCompleted',
properties: {
product_id: '12345',
amount: 99.99,
currency: 'USD'
},
time: Date.now(),
trace_id: 'unique-trace-id-12345',
anon_id: 'anonymous-user-id',
login_id: '[email protected]',
user_properties: {
plan: 'premium',
signup_date: '2024-01-01'
}
});User Profile
profileSet
Set user properties. If a property already exists, it will be overwritten.
Parameters:
properties(Object, required): User properties to set
Example:
SensorsWave.profileSet({
name: 'John Doe',
email: '[email protected]',
age: 30,
plan: 'premium'
});profileSetOnce
Set user properties only if they don't already exist. Existing properties will not be overwritten.
Parameters:
properties(Object, required): User properties to set once
Example:
SensorsWave.profileSetOnce({
signup_date: '2024-01-15',
initial_referrer: 'google',
initial_campaign: 'spring_sale'
});profileIncrement
Increment numeric user properties by a specified amount. Only supports numeric properties.
Parameters:
properties(Object, required): Properties to increment with numeric values
Example:
// Increment single property
SensorsWave.profileIncrement({
login_count: 1
});
// Increment multiple properties
SensorsWave.profileIncrement({
login_count: 1,
points_earned: 100,
purchases_count: 1
});profileAppend
Append new values to list-type user properties without deduplication.
Parameters:
properties(Object, required): Properties with array values to append
Example:
SensorsWave.profileAppend({
categories_viewed: ['electronics', 'mobile_phones'],
tags: ['new_customer', 'q1_2024']
});profileUnion
Append new values to list-type user properties with deduplication (avoids duplicate values).
Parameters:
properties(Object, required): Properties with array values to append with deduplication
Example:
SensorsWave.profileUnion({
interests: ['technology', 'gaming'],
newsletter_subscriptions: ['tech_news']
});profileUnset
Set specific user properties to null (effectively removing them).
Parameters:
propertyNames(string | string[], required): Property name(s) to unset
Example:
// Unset single property
SensorsWave.profileUnset('temporary_campaign');
// Unset multiple properties
SensorsWave.profileUnset(['old_plan', 'expired_flag', 'temp_id']);profileDelete
Delete all user profile data for the current user. This operation cannot be undone.
Example:
SensorsWave.profileDelete();User Identification
identify
Set the login ID for the current user and send a binding event to associate anonymous behavior with the identified user.
Parameters:
loginId(string | number, required): Unique identifier for the user (e.g., email, user ID, username)
Example:
SensorsWave.identify('[email protected]');setLoginId
Set the login ID for the current user without sending a binding event. Use this if you want to identify the user but don't need to track the association event.
Parameters:
loginId(string | number, required): Unique identifier for the user
Example:
SensorsWave.setLoginId('[email protected]');Common Properties
registerCommonProperties
Register static or dynamic common properties that will be included with all events. This is useful for including global context like app version, environment, or user-specific data.
Parameters:
properties(Record<string, string | Function>, required): Properties to register- Static properties: string values
- Dynamic properties: functions that return values (evaluated for each event)
Example:
SensorsWave.registerCommonProperties({
// Static property
app_version: '1.0.0',
environment: 'production',
// Dynamic property (evaluated for each event)
current_time: () => new Date().toISOString(),
user_session_id: () => getSessionId(),
// You can also include user-specific data
user_tier: () => getUserTier()
});clearCommonProperties
Remove specific registered common properties.
Parameters:
propertyNames(string[], required): Array of property names to remove
Example:
SensorsWave.clearCommonProperties(['app_version', 'user_session_id']);A/B Testing
checkFeatureGate
Check if a feature gate (feature flag) is enabled for the current user. Returns a promise that resolves to a boolean.
Parameters:
key(string, required): The feature gate key to check
Returns: Promise
Example:
// Check if a feature is enabled
SensorsWave.checkFeatureGate('new_checkout_flow')
.then(isEnabled => {
if (isEnabled) {
// Show new feature
showNewCheckout();
} else {
// Show old feature
showOldCheckout();
}
});
// Using async/await
async function initFeature() {
const isEnabled = await SensorsWave.checkFeatureGate('advanced_search');
if (isEnabled) {
enableAdvancedSearch();
}
}getExperiment
Get experiment variant data for the current user. Returns a promise that resolves to the experiment configuration.
Parameters:
key(string, required): The experiment key to retrieve
Returns: Promise
The returned object contains:
- Record<string, any>: Variant configuration values
Example:
// Get experiment configuration
SensorsWave.getExperiment('homepage_layout')
.then(experiment => {
if (experiment) {
// Apply experiment configuration
applyLayout(experiment.layout_type);
}
});
// Using async/await
async function initExperiment() {
const experiment = await SensorsWave.getExperiment('pricing_display');
if (experiment) {
const { price_format, discount_type } = experiment;
updatePricingDisplay(price_format, discount_type);
}
}Supported Event Types
The SDK automatically captures the following event types when autoCapture is enabled:
- PageView: Triggered when a user views a page
- PageLoad: Triggered when a page finishes loading
- PageLeave: Triggered when a user is about to leave a page
- WebClick: Triggered on element clicks (only when
enableClickTrackis true)
Custom events can be tracked using the trackEvent() or track() methods.
License
Apache-2.0
