/
aska
/
web-static-labs
Обзор
Документация
Войти
/
aska
/
web-static-labs
Код
Запросы
0
Задачи
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
html/lab6/task2/script.js
243 строки
8 KB
yourr
111
14 янв 2026, 14:18
14 янв 2026, 14:18
4d4f934
Код
Авторство
О чём код?
'use strict'; class CookieManager { constructor() { this.consentCookieName = 'cookie_consent'; this.userNameCookieName = 'userName'; this.consentTimeCookieName = 'consent_time'; this.tempUserName = null; this.init(); } init() { this.bindEvents(); this.checkExistingData(); } bindEvents() { // Основные кнопки document.getElementById('addCookie').addEventListener('click', () => this.handleAddUserName()); document.getElementById('removeCookie').addEventListener('click', () => this.removeUserName()); document.getElementById('clearAllCookies').addEventListener('click', () => this.clearAllCookies()); document.getElementById('changeConsent').addEventListener('click', () => this.showConsentBubble()); // Кнопки bubble окна document.getElementById('acceptBubble').addEventListener('click', () => this.acceptCookies()); document.getElementById('rejectBubble').addEventListener('click', () => this.rejectCookies()); document.getElementById('closeBubble').addEventListener('click', () => this.hideConsentBubble()); } checkExistingData() { const hasConsent = this.hasConsent(); if (hasConsent) { this.loadSavedData(); this.showResultArea(); } } handleAddUserName() { const userName = document.getElementById('userInput').value.trim(); if (!userName) { this.showStatus('Введите имя!', 'error'); return; } // Сохраняем имя временно this.tempUserName = userName; // Проверяем, есть ли уже согласие if (this.hasConsent()) { this.saveUserName(userName); this.showResultArea(); } else { // Показываем bubble окно для согласия this.showConsentBubble(); } } showConsentBubble() { const cookieBubble = document.getElementById('cookieBubble'); // Создаем overlay const overlay = document.createElement('div'); overlay.className = 'bubble-overlay'; overlay.id = 'bubbleOverlay'; document.body.appendChild(overlay); // Показываем bubble cookieBubble.style.display = 'block'; // Закрытие по клику на overlay overlay.addEventListener('click', () => this.hideConsentBubble()); } hideConsentBubble() { const cookieBubble = document.getElementById('cookieBubble'); const overlay = document.getElementById('bubbleOverlay'); cookieBubble.style.display = 'none'; if (overlay) { overlay.remove(); } // Очищаем временное имя если пользователь закрыл окно без выбора if (this.tempUserName && !this.hasConsent()) { this.tempUserName = null; document.getElementById('userInput').value = ''; } } acceptCookies() { this.setConsent('accepted'); this.setConsentTime(); // Сохраняем имя пользователя if (this.tempUserName) { this.saveUserName(this.tempUserName); } this.hideConsentBubble(); this.showResultArea(); this.showStatus('Cookie приняты! Ваше имя сохранено.', 'success'); } rejectCookies() { this.setConsent('rejected'); this.setConsentTime(); // Очищаем временное имя this.tempUserName = null; document.getElementById('userInput').value = ''; this.hideConsentBubble(); this.showResultArea(); this.showStatus('Cookie отклонены. Имя не будет сохранено.', 'warning'); } saveUserName(userName) { const safeName = encodeURIComponent(userName); document.cookie = `${this.userNameCookieName}=${safeName};max-age=2592000;path=/`; // 30 дней this.updateDisplay(); } removeUserName() { document.cookie = `${this.userNameCookieName}=;expires=${new Date(0).toUTCString()};path=/`; document.getElementById('userInput').value = ''; this.showStatus('Имя удалено из cookie', 'info'); this.updateDisplay(); } clearAllCookies() { if (confirm('Вы уверены, что хотите удалить все cookie? Это приведет к удалению вашего имени и настроек.')) { this.removeAllAppCookies(); document.getElementById('userInput').value = ''; this.tempUserName = null; this.showResultArea(); this.showStatus('Все cookie удалены', 'info'); this.updateDisplay(); } } removeAllAppCookies() { const cookies = document.cookie.split('; '); for (const cookie of cookies) { const [name] = cookie.split('='); if (name === this.userNameCookieName || name === this.consentCookieName || name === this.consentTimeCookieName) { document.cookie = `${name}=;expires=${new Date(0).toUTCString()};path=/`; } } } setConsent(status) { document.cookie = `${this.consentCookieName}=${status};max-age=2592000;path=/`; // 30 дней } setConsentTime() { const now = new Date().toISOString(); document.cookie = `${this.consentTimeCookieName}=${now};max-age=2592000;path=/`; } hasConsent() { return !!this.getCookie(this.consentCookieName); } getConsentStatus() { return this.getCookie(this.consentCookieName); } getConsentTime() { const time = this.getCookie(this.consentTimeCookieName); if (time) { return new Date(time).toLocaleString('ru-RU'); } return null; } getCookie(name) { const cookies = document.cookie.split('; '); for (const cookie of cookies) { const [key, value] = cookie.split('='); if (key === name) { return decodeURIComponent(value); } } return null; } loadSavedData() { const savedName = this.getCookie(this.userNameCookieName); if (savedName) { document.getElementById('userInput').value = savedName; } } showResultArea() { const resultArea = document.getElementById('resultArea'); resultArea.style.display = 'block'; this.updateDisplay(); } updateDisplay() { const userName = this.getCookie(this.userNameCookieName); const consentStatus = this.getConsentStatus(); const consentTime = this.getConsentTime(); const allCookies = document.cookie || 'Нет cookie'; document.getElementById('currentUserName').textContent = userName || '-'; let consentText = '-'; let consentColor = ''; switch (consentStatus) { case 'accepted': consentText = 'Принято'; break; case 'rejected': consentText = 'Отклонено'; break; default: consentText = 'Не предоставлено'; } document.getElementById('currentConsent').textContent = consentText; document.getElementById('cookieTime').textContent = consentTime || '-'; document.getElementById('allCookies').textContent = allCookies; } showStatus(message, type = 'info') { const statusElement = document.getElementById('status'); statusElement.textContent = message; statusElement.className = `status-message status-${type}`; setTimeout(() => { statusElement.textContent = ''; statusElement.className = 'status-message'; }, 4000); } } // Инициализация при загрузке DOM document.addEventListener('DOMContentLoaded', () => { new CookieManager(); });