-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbareboneanalytics-tracker.js
184 lines (159 loc) · 6.98 KB
/
bareboneanalytics-tracker.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
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
(function() {
const logUrl = 'https://your-server/api/track';
const observers = [];
const trackedElements = new Set();
// Retrieve client ID and environment from script URL query parameters
function getParamsFromScript() {
const scripts = document.getElementsByTagName('script');
for (let script of scripts) {
if (script.src.includes('bareboneanalytics-tracker.js')) {
const urlParams = new URLSearchParams(script.src.split('?')[1]);
const params = {
clientId: urlParams.get('client_id'),
environment: urlParams.get('environment') || 'production'
};
console.log('Barebone Analytics: Parameters:', params);
return params;
}
}
console.warn('Barebone Analytics: Script "bareboneanalyticstracker.js" not found.');
return { clientId: null, environment: 'production' };
}
const { clientId, environment } = getParamsFromScript();
// If no clientId is provided, do not proceed
if (!clientId) {
console.warn('Barebone Analytics: Tracking script disabled: client_id is missing.');
return;
}
function trackEvent(eventType, data) {
console.log(`Barebone Analytics: Logging ${eventType}:`, data);
const bodyData = {
clientId: clientId,
userId: getUserId(),
eventType: eventType,
environment: environment,
timestamp: new Date().toISOString()
};
if (eventType === 'impression')
bodyData.productIds = data;
else if (eventType === 'click')
bodyData.productIds = [data];
fetch(logUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(bodyData)
})
.catch(error => console.error(`Barebone Analytics: Error logging ${eventType}:`, error));
}
function trackImpressions(productIds) {
trackEvent('impression', productIds);
}
function trackClicks(productId) {
trackEvent('click', productId);
}
function getUserId() {
console.log('Barebone Analytics: Getting user ID from local storage: ', localStorage.getItem('userId'));
let userId = localStorage.getItem('userId');
if (!userId) {
userId = generateUUID();
localStorage.setItem('userId', userId);
}
return userId;
}
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
function handleClick(event) {
const productId = event.currentTarget.getAttribute('barebone-analytics-data-product-id');
trackClicks(productId);
}
function observeNewElements(observer) {
const mutationObserver = new MutationObserver(mutations => {
mutations.forEach(mutation => {
mutation.addedNodes.forEach(node => {
if (node.nodeType === Node.ELEMENT_NODE) {
const productElements = node.querySelectorAll('[barebone-analytics-data-product-id]');
if (node.hasAttribute('barebone-analytics-data-product-id')) {
observer.observe(node);
node.addEventListener('click', handleClick);
trackedElements.add({ element: node, event: handleClick });
}
productElements.forEach(product => {
observer.observe(product);
product.addEventListener('click', handleClick);
trackedElements.add({ element: product, event: handleClick });
});
}
});
mutation.removedNodes.forEach(node => {
if (node.nodeType === Node.ELEMENT_NODE) {
const productElements = node.querySelectorAll('[barebone-analytics-data-product-id]');
if (node.hasAttribute('barebone-analytics-data-product-id')) {
node.removeEventListener('click', handleClick);
trackedElements.delete({ element: node, event: handleClick });
}
productElements.forEach(product => {
product.removeEventListener('click', handleClick);
trackedElements.delete({ element: product, event: handleClick });
});
}
});
});
});
mutationObserver.observe(document.body, {
childList: true,
subtree: true
});
observers.push(mutationObserver);
}
function initTracking() {
console.log('Barebone Analytics: Initializing tracking...');
const products = document.querySelectorAll('[barebone-analytics-data-product-id]');
const impressionsLogged = new Set();
console.log('Barebone Analytics: Found products:', products);
const observer = new IntersectionObserver((entries) => {
const visibleProducts = [];
entries.forEach(entry => {
if (entry.isIntersecting) {
const productId = entry.target.getAttribute('barebone-analytics-data-product-id');
console.log('Barebone Analytics: Product visible:', productId);
if (!impressionsLogged.has(productId)) {
visibleProducts.push(productId);
impressionsLogged.add(productId);
}
}
});
if (visibleProducts.length > 0) {
console.log('Barebone Analytics: Visible products:', visibleProducts);
trackImpressions(visibleProducts);
}
}, {
root: null,
rootMargin: '0px',
threshold: 0.5 // Trigger when 50% of the product is visible
});
products.forEach(product => {
observer.observe(product);
product.addEventListener('click', handleClick);
trackedElements.add({ element: product, event: handleClick });
});
observers.push(observer);
observeNewElements(observer);
}
function cleanup() {
console.log('Barebone Analytics: Cleaning up tracking...');
observers.forEach(observer => observer.disconnect());
trackedElements.forEach(({ element, event }) => {
element.removeEventListener('click', event);
});
trackedElements.clear();
}
document.addEventListener('DOMContentLoaded', initTracking);
// Expose cleanup function to the global scope for testing purposes
window.trackingCleanup = cleanup;
})();