-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathanalytics.js
More file actions
72 lines (69 loc) · 2.25 KB
/
analytics.js
File metadata and controls
72 lines (69 loc) · 2.25 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const GA_ENDPOINT = "https://www.google-analytics.com/mp/collect";
const MEASUREMENT_ID = `G-J5KRWGVCW3`;
const API_SECRET = `A0QPsuDfRSqMFY-WUsGrdA`;
const SESSION_EXPIRATION_IN_MIN = 30;
const DEFAULT_ENGAGEMENT_TIME_IN_MSEC = 100;
async function getOrCreateSessionId() {
// Store session in memory storage
let { sessionData } = await chrome.storage.session.get("sessionData");
// Check if session exists and is still valid
const currentTimeInMs = Date.now();
if (sessionData && sessionData.timestamp) {
// Calculate how long ago the session was last updated
const durationInMin = (currentTimeInMs - sessionData.timestamp) / 60000;
// Check if last update lays past the session expiration threshold
if (durationInMin > SESSION_EXPIRATION_IN_MIN) {
// Delete old session id to start a new session
sessionData = null;
} else {
// Update timestamp to keep session alive
sessionData.timestamp = currentTimeInMs;
await chrome.storage.session.set({ sessionData });
}
}
if (!sessionData) {
// Create and store a new session
sessionData = {
session_id: currentTimeInMs.toString(),
timestamp: currentTimeInMs.toString(),
};
await chrome.storage.session.set({ sessionData });
}
return sessionData.session_id;
}
async function getOrCreateClientId() {
const result = await chrome.storage.local.get("clientId");
let clientId = result.clientId;
if (!clientId) {
clientId = self.crypto.randomUUID();
await chrome.storage.local.set({ clientId });
}
return clientId;
}
export async function reportEvent(eventName) {
const result = await chrome.storage.local.get("isInternal");
if (result.isInternal) {
console.log(`[Internal] got event ${eventName}`);
return;
}
try {
fetch(
`${GA_ENDPOINT}?measurement_id=${MEASUREMENT_ID}&api_secret=${API_SECRET}`,
{
method: "POST",
body: JSON.stringify({
client_id: await getOrCreateClientId(),
events: [
{
name: eventName,
params: {
session_id: await getOrCreateSessionId(),
engagement_time_msec: DEFAULT_ENGAGEMENT_TIME_IN_MSEC,
},
},
],
}),
}
);
} catch (error) {}
}