-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebclient.js
47 lines (42 loc) · 1.66 KB
/
webclient.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const E_PAGELOAD = "pageload";
const E_PAGELEAVE = "pageleave";
const E_KEYDOWN = "keydown";
const E_CLICK = "click";
const E_MOUSEMOVE = "mousemove";
const url = new URL(document.location).href;
let userActivityData = [];
function addUserActivityEvent(eventType, element, data) {
const el = element ? element.tagName + (element.id ? "#" + element.id : "") : undefined;
// NOTE: We stringify data as its schema can vary based on events
userActivityData.push({
url,
eventType,
timestamp: Date.now(),
data: JSON.stringify({ data, element }),
});
if (eventType == E_PAGELEAVE || eventType == E_PAGELOAD) sendDataToServer();
}
async function sendDataToServer() {
if (userActivityData.length <= 0) return;
const body = userActivityData.map((r) => JSON.stringify(r)).join("\n"); // NDJSON
userActivityData = [];
const headers = { "Content-Type": "application/x-ndjson", "x-bd-authorization": TAP_TOKEN };
const res = await fetch(TAP_URL, { method: "POST", headers, body });
if (!res.ok) console.error(res);
}
function getDeviceInfo() {
return {
ua: navigator.userAgent,
width: screen.width,
height: screen.height,
referrer: document.referrer,
};
}
const add = document.addEventListener;
const addW = window.addEventListener;
addUserActivityEvent(E_PAGELOAD, null, getDeviceInfo());
add("keydown", (event) => addUserActivityEvent(E_KEYDOWN, null, { key: event.key }));
add("click", (event) => addUserActivityEvent(E_CLICK, event.target));
add("mousemove", ({ clientX: x, clientY: y }) => addUserActivityEvent(E_MOUSEMOVE, null, { x, y }));
addW("beforeunload", () => addUserActivityEvent(E_PAGELEAVE));
setInterval(sendDataToServer, 5000);