UNPKG

pulsex

Version:

A lightweight and powerful JavaScript library for tracking user activity on websites. Easily monitor user interactions, including page visits, clicks, time spent, and engagement patterns. Designed for flexibility and performance, PulseX integrates seamles

1 lines 4.87 kB
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.PulseX=t():e.PulseX=t()}(this,(()=>(()=>{"use strict";var e={d:(t,n)=>{for(var o in n)e.o(n,o)&&!e.o(t,o)&&Object.defineProperty(t,o,{enumerable:!0,get:n[o]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{default:()=>s});const n="pulsex-session",o="pulsex_events",a=e=>{try{localStorage.setItem(o,JSON.stringify(e))}catch(e){console.error("PulseX: Error saving to localStorage:",e)}};class s{constructor(e){this.queue=[],this.engagementTrackingTasks=[],this.config=Object.assign({maxQueueSize:100},e);const t=localStorage.getItem(n);t?this.sessionId=t:(this.sessionId="session_"+Math.random().toString(16).substring(2,18),localStorage.setItem(n,this.sessionId)),this.loadQueue()}start(){this.startEngagementTracking(),this.setupVisibilityListener()}trackSectionEngagement(e,t){const n=document.getElementById(e);if(!n)return void console.warn(`PulseX: Element with ID ${e} not found`);const o={element:n,threshold:t};this.engagementTrackingTasks.push(o)}startEngagementTracking(){const e=new IntersectionObserver((e=>{e.forEach((e=>{if(e.isIntersecting){const t={sectionId:e.target.id,startTime:Date.now(),endTime:0,totalDuration:0},n=this.createBasePayload("section-engagement",t);this.queue.push(n)}else{const t=e.target.id,n=this.queue.find((e=>0===e.data.endTime&&e.data.sectionId===t));n&&(n.data.endTime=Date.now(),n.data.totalDuration=n.data.endTime-n.data.startTime);const o=this.engagementTrackingTasks.findIndex((e=>e.element.id===t)),a=this.engagementTrackingTasks[o];a&&n&&(null==n?void 0:n.data.totalDuration)>=(a.threshold||0)?this.saveQueueToLocalStorage():n&&this.queue.splice(o,1)}}))}),{threshold:.5});this.engagementTrackingTasks.forEach((t=>{t&&e.observe(t.element)}))}createBasePayload(e,t){return{_id:Math.random().toString(16).substring(2,18),sessionId:this.sessionId,type:e,data:t,pageUrl:window.location.href,referrer:document.referrer,createdAt:(new Date).toISOString()}}getQueue(){const e=localStorage.getItem("pulsex_events");return e?JSON.parse(e):[]}sendData(){return e=this,t=void 0,o=function*(){const e=this.getQueue();if(0===e.length)return;const t=(n=e,JSON.parse(JSON.stringify(n)));var n;this.clearQueue(),console.log("PulseX: Sending data...",t);try{if(!(yield fetch(this.config.apiEndpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).ok)throw new Error("Failed to send data")}catch(e){console.error("PulseX: Error sending data:",e),this.queue.unshift(...t),this.saveQueueToLocalStorage()}},new((n=void 0)||(n=Promise))((function(a,s){function i(e){try{c(o.next(e))}catch(e){s(e)}}function r(e){try{c(o.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?a(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,r)}c((o=o.apply(e,t||[])).next())}));var e,t,n,o}setupVisibilityListener(){window.addEventListener("visibilitychange",(()=>{"hidden"===document.visibilityState&&this.sendData()}))}saveQueueToLocalStorage(){a(this.queue)}clearQueue(){this.queue=[],a([])}loadQueue(){this.queue=(()=>{try{const e=localStorage.getItem(o);return e?JSON.parse(e):[]}catch(e){return console.error("PulseX: Error loading from localStorage:",e),[]}})()}trackClick(e){const t=document.getElementById(e);t?t.addEventListener("click",(e=>{const t=e.target,n={elementId:t.id,textContent:t.textContent||"",timestamp:Date.now(),x:e.clientX,y:e.clientY,button:e.button},o=this.createBasePayload("click",n);this.savePayloadToLocalStorage(o)})):console.warn(`PulseX: Element with ID ${e} not found`)}trackHover(e){const t=document.getElementById(e);if(!t)return void console.warn(`PulseX: Element with ID ${e} not found`);let n=0,o=!1,a=null;t.addEventListener("mouseover",(()=>{n=Date.now(),o=!1,a=null})),t.addEventListener("click",(e=>{o=!0;const t=e.target;a={elementId:t.id,textContent:t.textContent||"",timestamp:Date.now(),x:e.clientX,y:e.clientY,button:e.button}})),t.addEventListener("mouseout",(()=>{const t=Date.now(),s={elementId:e,startTime:n,endTime:t,hoverDuration:t-n,clicked:o,clickData:o?a:null},i=this.createBasePayload("hover",s);this.savePayloadToLocalStorage(i)}))}trackFormSubmission(e){const t=document.getElementById(e);t?t.addEventListener("submit",(n=>{n.preventDefault();const o={};new FormData(t).forEach(((e,t)=>{o[t]=e.toString()}));const a={formId:e,timestamp:Date.now(),inputValues:o},s=this.createBasePayload("form-submission",a);this.savePayloadToLocalStorage(s)})):console.warn(`PulseX: Form with ID ${e} not found`)}savePayloadToLocalStorage(e){const t=this.getQueue();t.push(e),a(t)}}return t})()));