towerops/assets/js/cookie_consent.js

53 lines
1.5 KiB
JavaScript

/**
* Cookie Consent Handler
*
* Handles cookie consent acceptance for GDPR compliance.
* Sets a cookie that expires in 1 year when the user accepts.
*/
export function initCookieConsent() {
// Check if consent cookie already exists on page load
if (hasConsentCookie()) {
hideBanner();
}
// Listen for click events on the accept button
document.addEventListener('click', (event) => {
if (event.target.matches('[data-cookie-consent="accept"]') ||
event.target.closest('[data-cookie-consent="accept"]')) {
acceptCookies();
}
});
}
function hasConsentCookie() {
return document.cookie.split('; ').some(cookie => cookie.startsWith('cookie_consent=accepted'));
}
function hideBanner() {
const banner = document.getElementById('cookie-consent-banner');
if (banner) {
banner.style.display = 'none';
}
}
function acceptCookies() {
// Set cookie that expires in 1 year
const expiryDate = new Date();
expiryDate.setFullYear(expiryDate.getFullYear() + 1);
// Only add Secure flag in production (requires HTTPS)
const isProduction = window.location.protocol === 'https:';
const secureFlag = isProduction ? '; Secure' : '';
document.cookie = `cookie_consent=accepted; expires=${expiryDate.toUTCString()}; path=/; SameSite=Lax${secureFlag}`;
// Hide the banner with animation
const banner = document.getElementById('cookie-consent-banner');
if (banner) {
banner.classList.add('opacity-0', 'translate-y-4');
setTimeout(() => {
banner.remove();
}, 200);
}
}