Sensors Wave JS SDK for web analytics
npm install @sensorswave/js-sdkSensorsWave 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.
``bash`
npm install @sensorswave/js-sdk
`javascript`
import SensorsWave from '@sensorswave/js-sdk';
SensorsWave.init('your-source-token', {
debug: false,
apiHost: 'https://your-api-host.com',
autoCapture: true
});
`html`
`javascript`
SensorsWave.trackEvent('ButtonClick', {
button_name: 'submit',
page: 'home'
});
| 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) |
#### 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:
`javascript`
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
- (Recordtime
- (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
Example:
`javascript`
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: 'user@example.com',
user_properties: {
plan: 'premium',
signup_date: '2024-01-01'
}
});
#### profileSet
Set user properties. If a property already exists, it will be overwritten.
Parameters:
- properties (Object, required): User properties to set
Example:
`javascript`
SensorsWave.profileSet({
name: 'John Doe',
email: 'john@example.com',
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:
`javascript`
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:
`javascript
// 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:
`javascript`
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:
`javascript`
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:
`javascript
// 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:
`javascript`
SensorsWave.profileDelete();
#### 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:
`javascript`
SensorsWave.identify('user@example.com');
#### 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:
`javascript`
SensorsWave.setLoginId('user@example.com');
#### 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
- Static properties: string values
- Dynamic properties: functions that return values (evaluated for each event)
Example:
`javascript
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:
`javascript`
SensorsWave.clearCommonProperties(['app_version', 'user_session_id']);
#### 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:
`javascript
// 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
Example:
`javascript
// 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);
}
}
`
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 enableClickTrack is true)
Custom events can be tracked using the trackEvent() or track()` methods.
Apache-2.0