@ram523/event-tracker-sdk
v1.0.12
Published
JavaScript SDK for EventTracker - A plug-and-play event tracking system for CRM/CTI applications
Maintainers
Readme
EventTracker SDK
A lightweight, plug-and-play JavaScript SDK for tracking user events in CRM/CTI applications. Perfect for tracking user interactions during call sessions and customer interactions.
Installation
npm install @anandvechalapu/eventtracker-sdkOr include directly in your HTML:
<script src="https://unpkg.com/@anandvechalapu/[email protected]/dist/browser.js"></script>Quick Start
1. Initialize the SDK
import EventTracker from '@anandvechalapu/eventtracker-sdk';
// Initialize when a CRM screen is opened (e.g., during an incoming call)
await EventTracker.init({
apiKey: 'your-api-key',
tenantId: 'tenant_001',
agentId: 'agent_123',
sessionId: 'session_456',
autoTrack: true // Enable all auto-tracking (default)
});2. Log Events
// Log custom events
await EventTracker.logEvent('appointmentBooked', {
patientId: 'p123',
appointmentDate: '2024-01-15',
doctorId: 'dr456'
});
await EventTracker.logEvent('reportViewed', {
reportId: 'r789',
reportType: 'medical',
duration: 45
});3. Close Session
// Close the ticket when the session ends
await EventTracker.closeTicket();React Integration
For React applications, use the provided hook for easy integration:
// hooks/useEventTracker.js
import { useEffect, useState } from 'react';
import EventTracker from '@eventtracker/sdk';
export const useEventTracker = (config) => {
const [isInitialized, setIsInitialized] = useState(false);
useEffect(() => {
const initializeSDK = async () => {
try {
await EventTracker.init({
...config,
autoTrack: true // Enable ALL auto-tracking
});
setIsInitialized(true);
console.log('Auto-tracking is now active!');
} catch (err) {
console.error('EventTracker failed:', err);
}
};
if (config?.apiKey) {
initializeSDK();
}
return () => {
if (isInitialized) {
EventTracker.closeTicket().catch(console.error);
}
};
}, [config?.apiKey]);
return { isInitialized };
};Use in your App component:
import React from 'react';
import { useEventTracker } from './hooks/useEventTracker';
function App() {
const { isInitialized } = useEventTracker({
apiKey: 'your-api-key',
tenantId: 'your-tenant-id',
agentId: 'agent-123',
sessionId: 'session-456'
});
return (
<div className="App">
<h1>My CRM Application</h1>
{isInitialized && <p>✓ Auto-tracking is active</p>}
{/* All interactions below are tracked automatically */}
<button onClick={() => console.log('Clicked!')}>
Sample Button
</button>
<form onSubmit={(e) => e.preventDefault()}>
<input type="text" placeholder="Type something..." />
<button type="submit">Submit</button>
</form>
</div>
);
}
export default App;See examples/react-integration.md for complete React setup guide.
Configuration Options
Auto-tracking Configuration
You can configure which events to track automatically:
await EventTracker.init({
apiKey: 'your-api-key',
tenantId: 'tenant_001',
agentId: 'agent_123',
sessionId: 'session_456',
autoTrack: {
pageVisits: true, // Track page loads and navigation
clicks: true, // Track button and link clicks
forms: true, // Track form submissions
inputs: true, // Track input changes and focus
scrolling: true, // Track scroll events
performance: true, // Track performance metrics
errors: true, // Track JavaScript errors
visibility: true // Track tab/window changes
}
});Advanced Configuration
await EventTracker.init({
apiKey: 'your-api-key',
tenantId: 'tenant_001',
agentId: 'agent_123',
sessionId: 'session_456',
baseUrl: 'https://your-server.com', // Custom server URL
autoTrack: false, // Disable auto-tracking
retryAttempts: 3, // Number of retry attempts
queueSize: 100, // Maximum events in queue
flushInterval: 5000 // Flush interval in milliseconds
});Features
✅ Comprehensive Auto-tracking
- Page visits: Navigation events, page loads, and user agent details
- Click tracking: All interactive elements (buttons, links, clickable areas)
- Form interactions: Submissions, field changes, and focus events
- Input monitoring: Debounced input changes and field focus tracking
- Scroll tracking: Throttled scroll events with position and percentage
- Performance metrics: Load times, DOM ready events, and navigation timing
- Error tracking: JavaScript errors and unhandled promise rejections
- Visibility events: Tab switching, window focus, and resize events
✅ Offline Support
- Event queuing: Events are queued when offline and sent when connection is restored
- Retry logic: Failed requests are automatically retried with exponential backoff
- Network detection: Automatically detects online/offline status
✅ Multi-tenant Support
- Tenant isolation: Each API key is tied to a specific tenant
- Data separation: All events are isolated per tenant for security
✅ Error Handling
- Graceful degradation: SDK continues to work even if some events fail
- Detailed logging: Comprehensive error logging for debugging
- Retry mechanisms: Automatic retry for failed requests
Configuration Options
await EventTracker.init({
apiKey: 'your-api-key', // Required: Your API key
tenantId: 'tenant_001', // Required: Tenant identifier
agentId: 'agent_123', // Required: Agent identifier
sessionId: 'session_456', // Required: Session identifier
baseUrl: 'https://your-api.com', // Optional: Custom API endpoint
autoTrack: true, // Optional: Enable auto-tracking (default: true)
retryAttempts: 3, // Optional: Number of retry attempts (default: 3)
queueSize: 100, // Optional: Maximum queue size (default: 100)
flushInterval: 5000 // Optional: Flush interval in ms (default: 5000)
});API Reference
EventTracker.init(config)
Initializes the SDK and creates a new tracking ticket.
Parameters:
config: Configuration object (see above)
Returns: Promise<void>
EventTracker.logEvent(eventType, eventData)
Logs a custom event.
Parameters:
eventType: String identifying the event typeeventData: Optional object containing event data
Returns: Promise<void>
EventTracker.closeTicket()
Closes the current tracking ticket and flushes any pending events.
Returns: Promise<void>
EventTracker.flush()
Immediately sends all queued events to the server.
Returns: Promise<void>
EventTracker.isInitialized()
Checks if the SDK is initialized.
Returns: boolean
EventTracker.getTicketId()
Gets the current ticket ID.
Returns: string | null
Usage Examples
React Integration
import { useEffect } from 'react';
import EventTracker from '@eventtracker/sdk';
function App() {
useEffect(() => {
// Initialize when component mounts
EventTracker.init({
apiKey: process.env.REACT_APP_EVENTTRACKER_API_KEY,
tenantId: 'tenant_001',
agentId: getCurrentAgentId(),
sessionId: getCurrentSessionId()
});
// Cleanup on unmount
return () => {
EventTracker.closeTicket();
};
}, []);
const handleAppointmentBook = async (appointmentData) => {
// Log the appointment booking event
await EventTracker.logEvent('appointmentBooked', appointmentData);
// Continue with your booking logic
await bookAppointment(appointmentData);
};
return (
<div>
<button onClick={() => handleAppointmentBook({ patientId: 'p123' })}>
Book Appointment
</button>
</div>
);
}Vanilla JavaScript
<!DOCTYPE html>
<html>
<head>
<title>CRM Application</title>
<script src="https://unpkg.com/@eventtracker/sdk/dist/index.js"></script>
</head>
<body>
<script>
// Initialize EventTracker when page loads
window.addEventListener('load', async () => {
await EventTracker.init({
apiKey: 'your-api-key',
tenantId: 'tenant_001',
agentId: 'agent_123',
sessionId: 'session_456'
});
});
// Log events on user actions
function onReportView(reportId) {
EventTracker.logEvent('reportViewed', {
reportId: reportId,
timestamp: new Date().toISOString()
});
}
// Close ticket when page unloads
window.addEventListener('beforeunload', () => {
EventTracker.closeTicket();
});
</script>
</body>
</html>Vue.js Integration
// main.js
import { createApp } from 'vue';
import EventTracker from '@eventtracker/sdk';
import App from './App.vue';
const app = createApp(App);
// Initialize EventTracker globally
app.config.globalProperties.$eventTracker = EventTracker;
// Initialize when app mounts
app.mount('#app');
EventTracker.init({
apiKey: process.env.VUE_APP_EVENTTRACKER_API_KEY,
tenantId: 'tenant_001',
agentId: 'agent_123',
sessionId: 'session_456'
});Event Types
The SDK supports any custom event type, but here are some common examples:
appointmentBooked- When an appointment is scheduledreportViewed- When a report is openedpatientSearched- When searching for patientscallStarted- When a call beginscallEnded- When a call endsnoteAdded- When a note is addeddocumentUploaded- When a document is uploadedreminderSet- When a reminder is created
Error Handling
The SDK includes comprehensive error handling:
try {
await EventTracker.logEvent('customEvent', { data: 'value' });
} catch (error) {
console.error('Failed to log event:', error);
// Event will be queued and retried automatically
}Browser Support
- Chrome 60+
- Firefox 55+
- Safari 11+
- Edge 79+
- Internet Explorer 11+ (with polyfills)
License
MIT
Support
For support, please contact our development team or create an issue in the repository.
