web-event-tracker-sdk
Version:
Auto-capture web events like page views, button clicks, and link clicks.
59 lines (58 loc) • 1.76 kB
JavaScript
var EventTracker = /** @class */ (function () {
function EventTracker() {
}
EventTracker.init = function (config) {
this.config = config;
if (config.autoCapture !== false) {
this.setupAutoCapture();
}
this.capturePageView();
};
EventTracker.setupAutoCapture = function () {
document.addEventListener('click', this.handleClick, true);
};
EventTracker.handleClick = function (event) {
var target = event.target;
if (!target)
return;
var 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.innerText || '',
href: target.href || '',
timestamp: Date.now(),
});
};
EventTracker.capturePageView = function () {
this.sendEvent({
type: 'page_view',
url: window.location.href,
title: document.title,
timestamp: Date.now(),
});
};
EventTracker.sendEvent = function (data) {
if (!this.config || !this.config.endpoint)
return;
fetch(this.config.endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': "Bearer ".concat(this.config.apiKey),
},
body: JSON.stringify(data),
}).catch(function () { });
};
return EventTracker;
}());
export default EventTracker;