UNPKG

overcentric

Version:

Overcentric watches your website, product, and users - and tells you what matters and what to do about it.

43 lines (42 loc) 1.72 kB
// Compute normalized hostname once when the module loads const normalizedHostname = typeof window !== 'undefined' ? window.location.hostname.replace(/^www\./, '') : ''; export function sendEvent(projectId, basePath, event, identity) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('POST', `${basePath}/events`, true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = () => { if (xhr.status >= 200 && xhr.status < 300) { resolve(); } else { reject(new Error(`HTTP Error: ${xhr.status} ${xhr.statusText}`)); } }; xhr.onerror = () => reject(new Error('Network Error')); const payload = { event: { name: event.eventName, properties: event.properties, project_id: projectId, device_id: event.deviceId, session_id: event.sessionId, context: event.context, url: window.location.href, hostname: normalizedHostname, ...(document.referrer && { referrer: document.referrer }), screen_width: window.screen.width, screen_height: window.screen.height }, ...(identity && identity.uniqueIdentifier && { identity: { project_id: projectId, unique_identifier: identity.uniqueIdentifier, email: identity.email, name: identity.name } }) }; xhr.send(JSON.stringify(payload)); }); }