UNPKG

web-event-tracker-sdk

Version:

Auto-capture web events like page views, button clicks, and link clicks.

64 lines (57 loc) 1.65 kB
type EventTrackerConfig = { apiKey: string; endpoint: string; autoCapture?: boolean; }; class EventTracker { private static config: EventTrackerConfig; static init(config: EventTrackerConfig) { this.config = config; if (config.autoCapture !== false) { this.setupAutoCapture(); } this.capturePageView(); } private static setupAutoCapture() { document.addEventListener('click', this.handleClick, true); } private static handleClick(event: MouseEvent) { const target = event.target as HTMLElement; if (!target) return; let eventType = ''; if (target.tagName === 'A') { eventType = 'link_click'; } else if (target.tagName === 'BUTTON') { eventType = 'button_click'; } else { eventType = 'element_click'; } EventTracker.sendEvent({ type: eventType, tag: target.tagName, text: (target as HTMLElement).innerText || '', href: (target as HTMLAnchorElement).href || '', timestamp: Date.now(), }); } private static capturePageView() { this.sendEvent({ type: 'page_view', url: window.location.href, title: document.title, timestamp: Date.now(), }); } static sendEvent(data: Record<string, any>) { if (!this.config || !this.config.endpoint) return; fetch(this.config.endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.config.apiKey}`, }, body: JSON.stringify(data), }).catch(() => {}); } } export default EventTracker;