@achado/web-analytics
v0.0.2
Published
Automatic web analytics tracking for Achado platform
Readme
@achado/web-analytics
Automatic web analytics tracking for the Achado platform. Tracks user interactions, page views, scroll depth, form interactions, and more without requiring manual tracking calls.
Installation
npm install @achado/core @achado/web-analyticsQuick Start
import { AchadoClient } from '@achado/core';
import { WebAnalytics } from '@achado/web-analytics';
const client = new AchadoClient({ apiKey: 'your-api-key' });
const webAnalytics = new WebAnalytics(client);
await client.initialize();
await webAnalytics.initialize();
// Analytics are now tracking automatically!Features
🔄 Automatic Page View Tracking
- Traditional page loads
- Single Page Application (SPA) navigation
- Time on page measurement
- Page exit tracking
👆 Click Tracking
- Button clicks
- Link clicks
- Custom elements with
data-track-click - Click coordinates and element context
📝 Form Analytics
- Form field focus/blur events
- Form submissions
- Field-level interaction tracking
- Privacy-safe value capture
📊 Scroll Depth Tracking
- Milestone tracking (25%, 50%, 75%, 100%)
- Maximum scroll depth per session
- Scroll velocity analytics
❌ Error Tracking
- JavaScript errors
- Promise rejections
- Custom error reporting
- Error context capture
🎵 Media Tracking
- Video/audio play, pause, ended events
- Progress milestones
- Engagement duration
- Media completion rates
💤 User Activity Tracking
- Inactivity detection
- Return behavior tracking
- Session engagement scoring
- Focus/blur detection
🚪 Exit Intent Detection
- Mouse movement-based detection
- Before unload events
- Exit prevention opportunities
Configuration
interface WebAnalyticsConfig {
enablePageViews?: boolean; // Default: true
enableClickTracking?: boolean; // Default: true
enableFormTracking?: boolean; // Default: true
enableScrollTracking?: boolean; // Default: true
enableErrorTracking?: boolean; // Default: true
enableInactivityTracking?: boolean; // Default: true
enableMediaTracking?: boolean; // Default: true
enableExitIntentTracking?: boolean; // Default: true
scrollThresholds?: number[]; // Default: [25, 50, 75, 100]
inactivityThreshold?: number; // Default: 300000 (5 minutes)
clickSelectors?: string[]; // Default: ['button', 'a', '[data-track-click]']
excludeSelectors?: string[]; // Default: ['[data-no-track]']
mediaSelectors?: string[]; // Default: ['video', 'audio']
}Example Configuration
const webAnalytics = new WebAnalytics(client, {
enablePageViews: true,
enableClickTracking: true,
enableFormTracking: true,
enableScrollTracking: true,
scrollThresholds: [10, 25, 50, 75, 90, 100],
inactivityThreshold: 120000, // 2 minutes
clickSelectors: ['button', 'a', '.trackable', '[data-track]'],
excludeSelectors: ['[data-no-track]', '.private'],
});API Reference
WebAnalytics Class
Constructor
new WebAnalytics(client: AchadoClient, config?: WebAnalyticsConfig)Methods
initialize(): Promise<void>
Start automatic tracking.
trackPageView(path?: string, title?: string): void
Manually track a page view.
webAnalytics.trackPageView('/custom-page', 'Custom Page Title');trackEvent(eventName: string, properties?: Record<string, any>): void
Track a custom event.
webAnalytics.trackEvent('video_shared', {
videoId: 'vid-123',
platform: 'twitter',
duration: 45,
});trackError(error: Error, context?: Record<string, any>): void
Manually track an error.
try {
// risky operation
} catch (error) {
webAnalytics.trackError(error, {
component: 'payment-form',
step: 'validation',
});
}getScrollProgress(): number
Get the maximum scroll percentage for the current page.
enableExitIntent(): void / disableExitIntent(): void
Control exit intent tracking.
updateConfig(config: Partial<WebAnalyticsConfig>): void
Update configuration at runtime.
getConfig(): WebAnalyticsConfig
Get current configuration.
destroy(): void
Stop tracking and clean up.
Tracked Events
Page Views
{
eventName: 'page_view',
properties: {
path: '/products',
title: 'Products - Achado',
url: 'https://example.com/products',
referrer: 'https://google.com',
search: '?category=analytics',
hash: '#features'
}
}Click Events
{
eventName: 'click',
properties: {
element: 'button#signup',
text: 'Sign Up Now',
href: null,
x: 245,
y: 156
}
}Form Interactions
{
eventName: 'form_interaction',
properties: {
formId: 'contact-form',
fieldName: 'email',
fieldType: 'email',
eventType: 'focus', // 'focus', 'blur', 'change', 'submit'
value: '[email protected]' // Only for non-sensitive fields
}
}Scroll Depth
{
eventName: 'scroll_depth',
properties: {
percentage: 50,
depth: 1200 // pixels
}
}Errors
{
eventName: 'javascript_error',
properties: {
message: 'Cannot read property of undefined',
filename: 'app.js',
lineno: 42,
colno: 15,
stack: '...'
}
}Privacy & Compliance
Data Protection
- Sensitive Data Filtering: Passwords, credit cards, SSNs automatically excluded
- Custom Exclusions: Use
data-no-trackto exclude elements - Value Masking: Form values masked for sensitive fields
- Configurable Tracking: Granular control over what gets tracked
Opt-out Support
// Disable specific tracking
webAnalytics.updateConfig({
enableFormTracking: false,
enableClickTracking: false,
});
// Or destroy completely
webAnalytics.destroy();GDPR Compliance
// Wait for consent before initializing
if (userHasConsented) {
await webAnalytics.initialize();
}
// Stop tracking if consent is withdrawn
webAnalytics.destroy();HTML Attributes
Track Specific Elements
<!-- Force tracking on any element -->
<div data-track-click>Custom tracking area</div>
<!-- Exclude from tracking -->
<button data-no-track>Private button</button>
<!-- Sensitive form fields -->
<input type="password" data-sensitive />
<input type="text" data-sensitive placeholder="SSN" />Media Tracking
<video controls data-track-media>
<source src="video.mp4" type="video/mp4" />
</video>
<audio controls data-track-media>
<source src="audio.mp3" type="audio/mpeg" />
</audio>Performance
- Passive Listeners: Non-blocking event listeners
- Debounced Tracking: Prevents event spam
- Efficient Selectors: Optimized DOM queries
- Minimal Overhead: < 1ms impact on user interactions
Browser Support
- Chrome 70+
- Firefox 65+
- Safari 12+
- Edge 79+
Examples
E-commerce Tracking
const webAnalytics = new WebAnalytics(client, {
enablePageViews: true,
enableClickTracking: true,
clickSelectors: [
'button',
'a',
'.product-card',
'.add-to-cart',
'.checkout-button',
],
excludeSelectors: ['.admin-only', '[data-internal]'],
});Content Site Tracking
const webAnalytics = new WebAnalytics(client, {
enableScrollTracking: true,
scrollThresholds: [10, 25, 50, 75, 90, 100],
enableMediaTracking: true,
mediaSelectors: ['video', 'audio', '.embedded-media'],
inactivityThreshold: 180000, // 3 minutes
});SaaS Application Tracking
const webAnalytics = new WebAnalytics(client, {
enableFormTracking: true,
enableErrorTracking: true,
enableInactivityTracking: true,
inactivityThreshold: 600000, // 10 minutes
clickSelectors: ['button', '.feature-button', '[data-action]', '.nav-item'],
});