web-collect-events
Version:
An sdk for collecting events from web pages
226 lines (225 loc) • 8.87 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const browserProfile_1 = __importDefault(require("./helpers/browserProfile"));
const dateTimeIndex_1 = __importDefault(require("./helpers/dateTimeIndex"));
const domNodeProfile_1 = __importDefault(require("./helpers/domNodeProfile"));
const validNode_1 = require("./helpers/validNode");
const api_1 = require("./helpers/api");
const userId_1 = __importDefault(require("./helpers/userId"));
const BASE_URL = "http://localhost:8080";
class GTETWebSDK {
constructor() {
// variables for scope
this.isPushNotificationScope = false;
this.isCustomEventScope = false;
// data storage
this._data = [];
this.checkScope();
this.initStorage();
console.log("GTETWebSDK started");
}
// initialize storage
initStorage() {
this._data = [];
}
// helper functions for data storage
setData(value) {
this._data.push(value);
}
getData() {
return this._data;
}
removeData() {
this._data = [];
}
// function to check scope of functions allowed to user
checkScope() {
this.isPushNotificationScope =
typeof window !== "undefined" && typeof navigator !== "undefined";
this.isCustomEventScope = typeof window !== "undefined";
}
handleDocumentClick(e) {
const targetNode = e.target;
console.log(targetNode);
if ((0, validNode_1.isNodeValid)(targetNode)) {
const data = {
event_name: "click",
event_data: {
browserProfile: (0, browserProfile_1.default)(),
dateTimeIndex: (0, dateTimeIndex_1.default)(),
userDetails: (0, userId_1.default)(),
domNodeProfile: (0, domNodeProfile_1.default)(e),
},
};
this.setData(data);
}
}
// function to register the user for services
registerUser(key) {
const url = `${BASE_URL || process.env.BASE_URL}/api/v1/register`;
if (!url) {
console.log("BASE_URL environment variable is not defined.");
return;
}
const headers = {
type: "application/json",
Authorization: `Bearer ${key}`,
};
fetch(url, {
method: "POST",
headers: headers,
body: JSON.stringify({
user_id: localStorage.getItem("userId"),
}),
});
}
// function to send the event data to the server using sendBeacon method
sendEventData() {
const url = `${BASE_URL || process.env.BASE_URL}/api/v1/event`;
if (!url) {
console.log("BASE_URL environment variable is not defined.");
return;
}
const jwtToken = localStorage.getItem("jwtToken") || "";
const headers = {
type: "application/json",
Authorization: `Bearer ${jwtToken}`,
};
const formdata = new FormData();
const bData = this.getData();
formdata.append("headers", JSON.stringify(headers));
formdata.append("data", JSON.stringify(bData));
if (bData.length > 0) {
navigator.sendBeacon(`${url}`, formdata);
}
this.removeData();
}
// function to self analyze the page and send data to the server
selfAnalyze() {
if (this.isCustomEventScope) {
document.addEventListener("click", this.handleDocumentClick.bind(this)); // Bind the event handler
document.addEventListener("visibilitychange", this.sendEventData.bind(this)); // Bind the event handler
setInterval(this.sendEventData.bind(this), 60000); // Bind the method
console.log("Self analyze started");
}
else {
console.log("This code is not running in a browser environment for selfAnalyze.");
}
}
// function to custom event send data to the server
customEvent(eventName, data) {
if (this.isCustomEventScope) {
const dataObject = {
event_name: eventName,
event_data: data,
};
this.sendCustomEvent(dataObject);
}
else {
console.log("This code is not running in a browser environment for customEvent.");
}
}
sendCustomEvent(data) {
const url = `${BASE_URL || process.env.BASE_URL}/api/v1/event`;
if (!url) {
console.log("BASE_URL environment variable is not defined.");
return;
}
const jwtToken = localStorage.getItem("jwtToken") || "";
const headers = {
type: "application/json",
Authorization: `Bearer ${jwtToken}`,
};
const formdata = new FormData();
const bData = data;
formdata.append("headers", JSON.stringify(headers));
formdata.append("data", JSON.stringify(bData));
navigator.sendBeacon(`${url}`, formdata);
}
// setContext function to set the context of the user
setContext(userContext) {
const url = `${BASE_URL || process.env.BASE_URL}/api/v1/user`;
if (!url) {
console.log("BASE_URL environment variable is not defined.");
return;
}
(0, api_1.postData)(url, userContext);
}
pushNotification(publicVapidKey, api, swfile) {
if (this.isPushNotificationScope) {
if ("serviceWorker" in navigator && "PushManager" in window) {
this.registerServiceWorker(swfile)
.then(() => this.sendSubscriptionToServer(publicVapidKey, api))
.catch((error) => console.error("Error:", error));
}
else {
console.log("Service Worker or PushManager is not supported in this browser.");
}
}
else {
console.log("This code is not running in a browser environment for pushNotification.");
}
}
registerServiceWorker(swfile) {
return __awaiter(this, void 0, void 0, function* () {
try {
const register = yield navigator.serviceWorker.register(`/${swfile}.js`, {
scope: "/",
});
console.log("Service Worker registered:", register);
}
catch (error) {
console.error("Failed to register Service Worker:", error);
throw error;
}
});
}
sendSubscriptionToServer(publicVapidKey, api) {
return __awaiter(this, void 0, void 0, function* () {
try {
const registration = yield navigator.serviceWorker.ready;
const subscription = yield registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: this.urlBase64ToUint8Array(publicVapidKey),
});
yield fetch(api, {
method: "POST",
body: JSON.stringify(subscription),
headers: {
"content-type": "application/json",
},
});
console.log("Push Sent...", JSON.stringify(subscription));
}
catch (error) {
console.error("Failed to send subscription to the server:", error);
throw error;
}
});
}
urlBase64ToUint8Array(base64String) {
const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, "+")
.replace(/_/g, "/");
const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);
for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
}
return outputArray;
}
}
exports.default = GTETWebSDK;