Title: JavaScript SDK Locale: en URL: https://sensorswave.com/en/docs/data-integration/client-sdks/javascript/ Description: JavaScript SDK integration guide and API reference The Sensors Wave JavaScript SDK is a client-side data collection and AB testing tool designed for web applications. ## Core Features The JavaScript SDK provides the following core capabilities: - **Event Tracking**: Manually track custom events and user behaviors - **AutoCapture**: Automatically collect page views, page loads, page leaves, clicks, and other events - **User Identification**: Support for Anonymous ID and Login ID identity association - **User Property Management**: Full User Property operations (set, append, increment, etc.) - **A/B Testing Integration**: Support for Feature Gate and experiment variable retrieval - **Single-Page Application Support**: Full support for route monitoring in React, Vue, Angular, and other SPA frameworks - **Batch Sending**: Optimized network request performance, sending up to 10 events in batches every 5 seconds - **Common Properties**: Support for static and dynamic common properties, automatically attached to all events ## Installation ### NPM Installation (or yarn, pnpm) ```bash npm install @sensorswave/js-sdk ``` ### Script Tag Import If your project doesn't use build tools, you can import it directly via a Script tag: ```html ``` > **Tip**: You can obtain the compiled file from the `dist` directory of the npm package, or use a CDN service. ## Quick Start ### Basic Initialization Initialize the SDK in your application entry file: **ES6 Module (Recommended)** ```javascript // Initialize the SDK SensorsWave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com', // Data reporting endpoint debug: false, // Debug mode autoCapture: true // Enable AutoCapture }); ``` **Script Tag** ```html SensorsWave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com', debug: false, autoCapture: true }); ``` ### Send Your First Event After initialization, you can start reporting events immediately: ```javascript // Track a button click SensorsWave.trackEvent('ButtonClick', { button_name: 'submit', page: 'home' }); ``` ## Configuration Options The second parameter of the `init` method is a configuration object that supports the following options: | Option | Type | Default | Description | |--------|------|--------|------| | `apiHost` | `string` | `''` | **Required**. API endpoint for data reporting. You can find it in Pipeline | | `debug` | `boolean` | `false` | Whether to enable debug mode; outputs detailed logs to the console when enabled | | `autoCapture` | `boolean` | `true` | Whether to enable AutoCapture for page views, loads, and leave events | | `enableClickTrack` | `boolean` | `false` | Whether to enable automatic click tracking (tracks major clickable elements) | | `isSinglePageApp` | `boolean` | `false` | Whether the app is a single-page application (SPA); auto-monitors route changes when enabled | | `crossSubdomainCookie` | `boolean` | `true` | Whether to support cross-subdomain cookie sharing (for cross-subdomain user identification) | | `batchSend` | `boolean` | `true` | Whether to use batch sending; sends up to 10 events every 5 seconds | | `enableAB` | `boolean` | `false` | Whether to enable A/B testing | | `abRefreshInterval` | `number` | `600000` | A/B testing configuration refresh interval (milliseconds), default 10 minutes | ### Complete Configuration Example ```javascript SensorsWave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com', debug: true, // Enable debug in development autoCapture: true, // Enable AutoCapture enableClickTrack: true, // Enable click tracking isSinglePageApp: true, // SPA mode crossSubdomainCookie: true, // Cross-subdomain user identity sharing batchSend: true, // Batch sending for performance enableAB: true, // Enable A/B testing abRefreshInterval: 10 * 60 * 1000 // Refresh A/B test data every 10 minutes }); ``` > **Tip**: In production, it is recommended to disable `debug` mode to avoid excessive logging in the browser console. ## API Methods ### Event Tracking #### trackEvent - Track Custom Events Manually track custom events and their properties. **Parameters**: - `eventName` (string, required): Event name - `properties` (Object, optional): Event properties as key-value pairs **Example**: ```javascript // Track a button click SensorsWave.trackEvent('ButtonClick', { button_name: 'submit', page: 'home' }); ``` **Real-world examples**: ```javascript // E-commerce: user views a product SensorsWave.trackEvent('ProductView', { product_id: '12345', product_name: 'Wireless Bluetooth Headphones', category: 'Electronics', price: 299.00, currency: 'CNY' }); // E-commerce: user adds to cart SensorsWave.trackEvent('AddToCart', { product_id: '12345', quantity: 1, price: 299.00 }); // Content platform: article read SensorsWave.trackEvent('ArticleRead', { article_id: 'article_001', title: 'JavaScript Performance Optimization Tips', category: 'Tech Blog', read_duration: 120 // Reading duration (seconds) }); ``` #### track - Advanced Event Tracking Send a fully-populated event object for more granular control. This method allows you to manually specify all event fields. **Parameters**: - `event` (AdvanceEvent, required): Full event object containing the following fields: - `event` (string, required): Event name - `properties` (Record, optional): Event properties - `time` (number, required): Timestamp (milliseconds) - `anon_id` (string, optional): Anonymous user ID - `login_id` (string, optional): Logged-in user ID. At least one of login_id or anon_id must be provided; when both are provided, login_id takes priority - `trace_id` (string, required): Request Trace ID - `user_properties` (Record, optional): User properties **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_12345', user_properties: { // $set: insert or update a User Property $set: { plan: 'premium', signup_date: '2024-01-01' } } }); ``` > **Note**: The `track` method is an advanced feature. For most scenarios, `trackEvent` is sufficient. ### User Identification #### identify - Set Login User ID Set the Login user ID and send a binding event to associate anonymous behavior with the identified user. **Parameters**: - `loginId` (string | number, required): User's unique identifier (e.g., email, user ID, username) **Example**: ```javascript // Set user ID after login SensorsWave.identify('user_12345'); ``` **Complete login flow example**: ```javascript // User login flow async function handleUserLogin(email, password) { try { // Call login API const response = await fetch('/api/login', { method: 'POST', body: JSON.stringify({ email, password }) }); const { userId } = await response.json(); // Set user ID and associate anonymous behavior SensorsWave.identify(userId); } catch (error) { console.error('Login failed:', error); } } ``` > **Important**: If the `loginId` contains sensitive information (such as phone numbers, email addresses, ID numbers, etc.), please encrypt it before transmission to avoid sending sensitive data in plain text. #### setLoginId - Set Login ID Only Set the Login user ID without sending a binding event. Use this if you only want to identify the user without associating their identity. **Parameters**: - `loginId` (string | number, required): User's unique identifier **Example**: ```javascript SensorsWave.setLoginId('user_12345'); ``` > **Important**: If the `loginId` contains sensitive information (such as phone numbers, email addresses, ID numbers, etc.), please encrypt it before transmission to avoid sending sensitive data in plain text. > **Usage recommendation**: In most cases, the `identify` method is recommended because it records the user identity association event, which aids in subsequent analysis. #### getLoginId - Get Current Login ID Get the current Login ID for the identified user. **Returns**: string | number **Example**: ```javascript const loginId = SensorsWave.getLoginId(); console.log('Current login ID:', loginId); ``` #### getAnonId - Get Anonymous ID Get the current anonymous ID for the user. This ID is automatically generated and persists across sessions. **Returns**: string **Example**: ```javascript const anonId = SensorsWave.getAnonId(); console.log('Anonymous user ID:', anonId); ``` ### User Properties User Properties describe user characteristics such as membership level, registration time, preferences, etc. Unlike Event Properties, User Properties are persistently stored and associated with the user. #### profileSet - Set User Properties Set User Properties, overwriting if they already exist. **Parameters**: - `properties` (Object, required): User properties to set **Example**: ```javascript // Set User Properties after registration SensorsWave.profileSet({ name: 'John Doe', age: 30, plan: 'premium' }); ``` #### profileSetOnce - Set Only Once Set User Properties only if they don't already exist; existing properties will not be overwritten. **Parameters**: - `properties` (Object, required): User properties to set **Example**: ```javascript // Record first visit info (recorded once, never overwritten) SensorsWave.profileSetOnce({ signup_date: '2024-01-15', initial_referrer: 'google', initial_campaign: 'spring_sale' }); ``` #### profileIncrement - Increment Numeric Properties Perform increment operations on numeric User Properties. Only supports numeric properties. **Parameters**: - `properties` (Object, required): Properties and their increment values **Example**: ```javascript // Increment a single property SensorsWave.profileIncrement({ login_count: 1 }); // Increment multiple properties SensorsWave.profileIncrement({ login_count: 1, points_earned: 100, purchases_count: 1 }); ``` #### profileAppend - Append to Array Properties Append new values to array-type User Properties without deduplication. **Parameters**: - `properties` (Object, required): Properties and their array values to append **Example**: ```javascript SensorsWave.profileAppend({ categories_viewed: ['electronics', 'mobile_phones'], tags: ['new_customer', 'q1_2024'] }); ``` #### profileUnion - Append to Set Properties (Deduplicated) Append new values to array-type User Properties with automatic deduplication. **Parameters**: - `properties` (Object, required): Properties and their array values to append **Example**: ```javascript // First call SensorsWave.profileUnion({ interests: ['technology', 'gaming'] }); // Second call, 'technology' will not be added again SensorsWave.profileUnion({ interests: ['technology', 'music'] // Only 'music' will be added }); ``` #### profileUnset - Delete Specified Properties Set specified User Properties to null. **Parameters**: - `propertyNames` (string | string[], required): Property name or array of property names to set to null **Example**: ```javascript // Unset a single property SensorsWave.profileUnset('temporary_campaign'); // Unset multiple properties SensorsWave.profileUnset(['old_plan', 'expired_flag', 'temp_id']); ``` #### profileDelete - Delete All User Properties Delete all User Property data for the current user. This operation is irreversible. **Example**: ```javascript // Delete all User Properties when the user deactivates their account SensorsWave.profileDelete(); ``` > **Warning**: `profileDelete` deletes all User Properties. Use with caution. #### User Property Usage Example **Membership upgrade scenario**: ```javascript function handleMembershipUpgrade(newPlan) { // Update membership level and upgrade time SensorsWave.profileSet({ plan: newPlan, upgrade_time: new Date().toISOString() }); // Increment upgrade count SensorsWave.profileIncrement({ upgrade_count: 1 }); // Track upgrade event SensorsWave.trackEvent('membershipUpgrade', { from_plan: 'basic', to_plan: newPlan }); } ``` ### Common Properties Common properties are automatically added to all events, suitable for universal information that should be included in every event. Supports static properties (string values) and dynamic properties (function return values). #### registerCommonProperties - Register Common Properties Register static or dynamic common properties that will be automatically included in all events. **Parameters**: - `properties` (Record, required): Properties to register - Static property: string value - Dynamic property: function (called each time an event is sent) **Example**: ```javascript SensorsWave.registerCommonProperties({ // Static properties app_version: '1.0.0', environment: 'production', // Dynamic properties (called each time an event is sent) current_time: () => new Date().toISOString(), user_session_id: () => getSessionId(), // User-related dynamic data user_tier: () => getUserTier() }); ``` #### clearCommonProperties - Clear Common Properties Remove specified registered common properties. **Parameters**: - `propertyNames` (string[], required): Array of property names to remove **Example**: ```javascript SensorsWave.clearCommonProperties(['app_version', 'user_session_id']); ``` > **Note**: Common properties increase the data size of every event. Only add truly necessary universal properties. ### A/B Testing The JavaScript SDK has built-in A/B testing support for retrieving Feature Gate states and experiment variables. #### Enable A/B Testing ```javascript SensorsWave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com', enableAB: true, // Enable A/B testing abRefreshInterval: 10 * 60 * 1000 // Configuration refresh interval (10 minutes) }); ``` #### checkFeatureGate - Check Feature Gate Check whether a Feature Gate is enabled for the current user. Returns a Promise resolving to a boolean. **Parameters**: - `key` (string, required): Key of the Feature Gate **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 Variables Get the current user's experiment variable data. Returns a Promise resolving to an experiment configuration object. **Parameters**: - `key` (string, required): Key of the Experiment **Returns**: Promise The returned object contains the experiment's variable configuration values (Record). **Example**: ```javascript // Get experiment configuration SensorsWave.getExperiment('pricing_display') .then(experiment => { if (experiment) { // Apply experiment configuration const { price_format, discount_type } = experiment; updatePricingDisplay(price_format, discount_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); } } ``` **Complete A/B testing example**: ```javascript // E-commerce homepage CTA button A/B test async function initHomepageCTA() { try { const experiment = await SensorsWave.getExperiment('homepage_cta_test'); if (experiment) { const { button_text, button_color, button_size } = experiment; const ctaButton = document.getElementById('cta-button'); ctaButton.textContent = button_text || 'Buy Now'; ctaButton.style.backgroundColor = button_color || '#ff6600'; ctaButton.style.fontSize = button_size || '16px'; } } catch (error) { console.error('Failed to get experiment variables:', error); // Use default configuration } } // Initialize on page load initHomepageCTA(); ``` > **Tip**: A/B testing features require configuring experiments and Feature Gates in the Sensors Wave dashboard before use. ## AutoCapture When AutoCapture is enabled, the SDK automatically collects the following event types: | Event Name | Description | Trigger Timing | |---------|------|---------| | `$PageView` | Page view | When a user visits a page | | `$PageLoad` | Page load complete | When page loading completes | | `$PageLeave` | Page leave | When a user is about to leave a page | | `$WebClick` | Element click | When a user clicks an element (requires `enableClickTrack`) | ### Enable AutoCapture ```javascript SensorsWave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com', autoCapture: true, // Enable AutoCapture enableClickTrack: true // Enable automatic click tracking }); ``` ### Single-Page Application (SPA) Support If your application uses React, Vue, Angular, or other SPA frameworks, enable the `isSinglePageApp` option: ```javascript SensorsWave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com', autoCapture: true, isSinglePageApp: true // Enable SPA mode, auto-monitors route changes }); ``` In SPA mode, the SDK automatically monitors route changes and sends `$PageView` events. > **Tip**: AutoCapture can significantly reduce manual coding effort but increases data volume. Enable selectively based on actual needs. ## Framework Integration Examples ### React Integration ```javascript // src/utils/analytics.js SensorsWave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com', isSinglePageApp: true, // React is an SPA autoCapture: true }); ``` ```javascript // src/App.js function ProductDetail({ productId }) { useEffect(() => { // Track event when component loads SensorsWave.trackEvent('ProductView', { product_id: productId }); }, [productId]); return ...; } ``` ### Vue Integration ```javascript // src/plugins/analytics.js install(app) { SensorsWave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com', isSinglePageApp: true, autoCapture: true }); // Mount to global properties app.config.globalProperties.$analytics = SensorsWave; } }; ``` ```javascript // src/main.js const app = createApp(App); app.use(analytics); app.mount('#app'); ``` ```vue const { proxy } = getCurrentInstance(); function handleAddToCart() { proxy.$analytics.trackEvent('AddToCart', { product_id: 'SKU-12345' }); } ``` ## Important Notes ### Performance Optimization - Avoid calling `trackEvent` frequently in loops; consider merging events or using throttling - Batch sending is enabled by default, effectively reducing network requests - AutoCapture adds some performance overhead; enable only when needed ### Data Security - Do not pass sensitive information in event properties (e.g., passwords, credit card numbers, ID numbers) - Keep the Source Token secure; avoid exposing it in public code repositories - Cross-origin requests require the data reporting endpoint to support CORS ### Browser Compatibility - Supports Chrome, Firefox, Safari, Edge, and other modern browsers - Does not support IE 11 and earlier versions ### Data Loss Risk - Client-side tracking may be affected by ad blockers, causing approximately 10-20% data loss - For critical business data, server-side tracking is recommended. See [Tracking Strategy](../tracking-strategy.mdx) - When using the `beforeunload` event to track page leaves, some browsers may not send the request ## FAQ ### Why isn't my data being reported successfully? Check the following: 1. **Is the Source Token correct**: Confirm the `sourceToken` parameter is correct 2. **Is the reporting endpoint correct**: Confirm the `apiHost` configuration is correct 3. **Network connection**: Open browser developer tools (F12) → Network tab to check for failed requests 4. **Cross-origin issues**: Confirm the data reporting endpoint supports CORS 5. **Ad blockers**: Some ad blockers intercept data collection requests; try disabling them for testing 6. **Debug mode**: Enable `debug: true` to check console logs ### How do I avoid sending data in the development environment? ```javascript const isDevelopment = process.env.NODE_ENV === 'development'; if (!isDevelopment) { SensorsWave.init('YOUR_SOURCE_TOKEN', { apiHost: 'https://your-api-endpoint.com' }); } // Wrap a safe tracking method function trackEvent(eventName, properties) { if (!isDevelopment) { SensorsWave.trackEvent(eventName, properties); } else { console.log('[Analytics]', eventName, properties); } } // Usage example trackEvent('ButtonClick', { button_name: 'submit' }); ``` ## Related Documentation - [Tracking Strategy](../tracking-strategy.mdx): Understand the pros and cons of server-side and client-side tracking - [How to Properly Identify Users](../user-identification.mdx): Best practices for user identity recognition - [Data Model](../data-model.mdx): Understand the Sensors Wave data structure - [Events and Properties](../events-and-properties.mdx): Event design guidelines and best practices --- **Last updated**: January 19, 2026 **License**: Apache-2.0