-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsite-integration.js
More file actions
394 lines (338 loc) · 13.5 KB
/
website-integration.js
File metadata and controls
394 lines (338 loc) · 13.5 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
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
// Website Integration Script for Premium Carpets Co
// This script detects Cookiebot consent changes and triggers the Chrome extension
(function() {
'use strict';
console.log('🔧 Premium Carpets Co - Cookiebot Integration Loaded');
// Configuration
const CONFIG = {
websiteName: 'Premium Carpets Co',
websiteUrl: 'https://vermillion-zuccutto-ed1811.netlify.app/',
extensionName: 'GTM Consent Mode Inspector',
debugMode: false // Set to false for production
};
// State tracking
let consentState = {
analytics: null,
advertising: null,
functionality: null,
personalization: null,
necessary: null,
lastUpdate: null
};
let extensionDetected = false;
let consentChangeCount = 0;
// Generate cryptographically secure random ID
function generateSecureId() {
const array = new Uint8Array(16);
crypto.getRandomValues(array);
return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
}
// Secure logging utility
function log(message, type = 'info') {
// Only log in development mode
if (CONFIG.debugMode && process.env.NODE_ENV === 'development') {
const timestamp = new Date().toLocaleTimeString();
// Sanitize message to avoid exposing sensitive data
const sanitizedMessage = sanitizeLogMessage(message);
console.log(`[GTM Inspector] [${timestamp}] ${sanitizedMessage}`);
}
}
// Sanitize log messages to prevent sensitive data exposure
function sanitizeLogMessage(message) {
if (typeof message !== 'string') {
return '[Object]';
}
// Remove sensitive patterns
const sensitivePatterns = [
/https?:\/\/[^\s]+/g, // URLs
/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g, // Email addresses
/\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b/g, // Credit card numbers
/[A-Z]{2}\d{2}[A-Z0-9]{10,30}/g, // IBAN
/[A-Z]{3}\d{6}/g, // Passport numbers
];
let sanitized = message;
sensitivePatterns.forEach(pattern => {
sanitized = sanitized.replace(pattern, '[REDACTED]');
});
return sanitized;
}
function getCurrentConsent() {
if (window.Cookiebot && window.Cookiebot.consent) {
return {
analytics: window.Cookiebot.consent.analytics,
advertising: window.Cookiebot.consent.advertising,
functionality: window.Cookiebot.consent.functionality,
personalization: window.Cookiebot.consent.personalization,
necessary: window.Cookiebot.consent.necessary
};
}
return null;
}
function hasConsentChanged(newConsent) {
if (!newConsent) return false;
const oldConsent = consentState;
return (
oldConsent.analytics !== newConsent.analytics ||
oldConsent.advertising !== newConsent.advertising ||
oldConsent.functionality !== newConsent.functionality ||
oldConsent.personalization !== newConsent.personalization ||
oldConsent.necessary !== newConsent.necessary
);
}
function updateConsentState(newConsent) {
consentState = { ...newConsent, lastUpdate: Date.now() };
consentChangeCount++;
log(`Consent state updated (change #${consentChangeCount})`, 'success');
// Don't log sensitive consent data
log(`Consent categories updated`, 'info');
}
// Chrome Extension Detection
function detectChromeExtension() {
// Method 1: Check for extension content script
if (window.gtmInspectorContentLoaded) {
extensionDetected = true;
log('Chrome extension detected via content script', 'success');
return true;
}
// Method 2: Check for extension injected script
if (window.ConsentInspector) {
extensionDetected = true;
log('Chrome extension detected via injected script', 'success');
return true;
}
// Method 3: Try to communicate with extension
if (window.chrome && window.chrome.runtime) {
try {
// This will only work if the extension is installed and active
chrome.runtime.sendMessage('ping', (response) => {
if (response && response.success) {
extensionDetected = true;
log('Chrome extension detected via runtime message', 'success');
}
});
} catch (e) {
// Extension not available
}
}
return false;
}
// Trigger extension notification
function triggerExtensionNotification(consentAction) {
if (!extensionDetected) {
log('Extension not detected, attempting to detect...', 'warning');
detectChromeExtension();
}
const notificationData = {
website: CONFIG.websiteName,
url: window.location.href,
action: consentAction,
consent: getCurrentConsent(),
id: generateSecureId(),
timestamp: Date.now(),
changeCount: consentChangeCount
};
log(`Triggering extension notification for: ${consentAction}`, 'info');
// Method 1: Post message to extension
window.postMessage({
type: 'COOKIEBOT_CONSENT_CHANGE',
data: notificationData
}, window.location.origin);
// Method 2: Custom event
const event = new CustomEvent('cookiebotConsentChange', {
detail: notificationData
});
window.dispatchEvent(event);
// Method 3: Try to communicate with extension directly
if (window.chrome && window.chrome.runtime) {
try {
chrome.runtime.sendMessage({
action: 'cookiebotConsentChange',
data: notificationData
});
} catch (e) {
// Extension not available
}
}
// Method 4: Update dataLayer for GTM integration
if (window.dataLayer) {
window.dataLayer.push({
'event': 'cookiebot_consent_change',
'consent_action': consentAction,
'consent_data': notificationData,
'extension_triggered': extensionDetected
});
}
}
// Consent change handlers
function handleConsentChange(action) {
const currentConsent = getCurrentConsent();
if (!currentConsent) {
log('No consent data available', 'warning');
return;
}
if (hasConsentChanged(currentConsent)) {
updateConsentState(currentConsent);
triggerExtensionNotification(action);
// Show visual indicator
showConsentIndicator(action);
} else {
log('No consent change detected', 'info');
}
}
// Visual indicator for consent changes
function showConsentIndicator(action) {
// Remove existing indicator
const existingIndicator = document.getElementById('consent-change-indicator');
if (existingIndicator) {
existingIndicator.remove();
}
// Create new indicator
const indicator = document.createElement('div');
indicator.id = 'consent-change-indicator';
indicator.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: ${action === 'accept' ? '#28a745' : '#dc3545'};
color: white;
padding: 15px 20px;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
z-index: 10000;
font-family: Arial, sans-serif;
font-size: 14px;
max-width: 300px;
animation: slideIn 0.3s ease-out;
`;
const icon = action === 'accept' ? '✅' : '❌';
const message = action === 'accept' ?
'Cookies accepted! Chrome extension notified.' :
'Cookies rejected! Chrome extension notified.';
indicator.innerHTML = `
<div style="display: flex; align-items: center; gap: 10px;">
<span style="font-size: 18px;">${icon}</span>
<div>
<div style="font-weight: bold;">${CONFIG.extensionName}</div>
<div style="font-size: 12px; opacity: 0.9;">${message}</div>
</div>
</div>
`;
// Add CSS animation
const style = document.createElement('style');
style.textContent = `
@keyframes slideIn {
from { transform: translateX(100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
`;
document.head.appendChild(style);
document.body.appendChild(indicator);
// Auto-remove after 5 seconds
setTimeout(() => {
if (indicator.parentNode) {
indicator.style.animation = 'slideOut 0.3s ease-in';
setTimeout(() => {
if (indicator.parentNode) {
indicator.remove();
}
}, 300);
}
}, 5000);
// Add slideOut animation
const slideOutStyle = document.createElement('style');
slideOutStyle.textContent = `
@keyframes slideOut {
from { transform: translateX(0); opacity: 1; }
to { transform: translateX(100%); opacity: 0; }
}
`;
document.head.appendChild(slideOutStyle);
}
// Event listeners for Cookiebot
function setupCookiebotListeners() {
// Cookiebot load event
window.addEventListener('CookiebotOnLoad', function() {
log('Cookiebot loaded', 'success');
detectChromeExtension();
// Check initial consent state
const initialConsent = getCurrentConsent();
if (initialConsent) {
updateConsentState(initialConsent);
log('Initial consent state detected', 'info');
}
});
// Cookiebot accept event
window.addEventListener('CookiebotOnAccept', function() {
log('Cookiebot accept event fired', 'success');
handleConsentChange('accept');
});
// Cookiebot decline event
window.addEventListener('CookiebotOnDecline', function() {
log('Cookiebot decline event fired', 'success');
handleConsentChange('decline');
});
// Cookiebot consent update event
window.addEventListener('CookiebotOnConsentReady', function() {
log('Cookiebot consent ready event fired', 'success');
const consent = getCurrentConsent();
if (consent) {
updateConsentState(consent);
triggerExtensionNotification('update');
}
});
// Listen for manual consent changes
window.addEventListener('CookiebotOnDialogInit', function() {
log('Cookiebot dialog initialized', 'info');
});
window.addEventListener('CookiebotOnDialogDisplay', function() {
log('Cookiebot dialog displayed', 'info');
});
}
// Monitor for consent changes
function startConsentMonitoring() {
let lastConsent = getCurrentConsent();
setInterval(() => {
const currentConsent = getCurrentConsent();
if (currentConsent && lastConsent) {
if (hasConsentChanged(currentConsent)) {
log('Consent change detected via monitoring', 'info');
updateConsentState(currentConsent);
triggerExtensionNotification('monitor');
}
}
lastConsent = currentConsent;
}, 2000); // Check every 2 seconds
}
// Initialize integration
function initialize() {
log('Initializing Premium Carpets Co Cookiebot integration...', 'info');
// Setup event listeners
setupCookiebotListeners();
// Start monitoring
startConsentMonitoring();
// Detect extension
detectChromeExtension();
// Check if Cookiebot is already loaded
if (window.Cookiebot) {
log('Cookiebot already loaded, checking consent state', 'info');
const consent = getCurrentConsent();
if (consent) {
updateConsentState(consent);
}
}
log('Integration initialized successfully', 'success');
}
// Start integration when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initialize);
} else {
initialize();
}
// Export for external access
window.PremiumCarpetsCookiebotIntegration = {
getConsentState: () => consentState,
getExtensionDetected: () => extensionDetected,
triggerNotification: triggerExtensionNotification,
log: log
};
})();