JavaScript改造:实现用户Cookie偏好双向持久化存储
现有代码仅为「接受」操作保存了Cookie状态,「拒绝」操作未做持久化处理,且判断逻辑未区分用户选择就加载GA。以下是针对性修改方案:
核心改动点
- 为「拒绝」按钮添加Cookie设置,将用户选择状态保存30天
- 优化Cookie存储结构,用
cookieConsent字段明确记录用户选择(accept/decline) - 调整判断逻辑:存在Cookie时,仅用户选择「接受」才加载Google Analytics;无论接受/拒绝,都不再显示横幅
修改后的完整代码
// COOKIES START // ---- ---- Const ---- ---- // const cookiesBox = document.querySelector(".privacy-container"), buttons = document.querySelectorAll(".button"); // ---- ---- Show ---- ---- // const executeCodes = () => { // 查找是否存在Cookie选择记录 const consentCookie = document.cookie.split('; ').find(row => row.startsWith('cookieConsent=')); if (consentCookie) { const consentStatus = consentCookie.split('=')[1]; // 仅用户接受时加载GA if (consentStatus === 'accept') { loadGoogleAnalytics(); } // 已有选择记录,不再显示横幅 return; } cookiesBox.classList.add("show"); // ---- ---- Button ---- ---- // buttons.forEach((button) => { button.addEventListener("click", () => { cookiesBox.classList.remove("show"); const maxAge = 60 * 60 * 24 * 30; // 30天有效期 if (button.id === "acceptBtn") { document.cookie = `cookieConsent=accept; max-age=${maxAge}`; loadGoogleAnalytics(); } else if (button.id === "declineBtn") { // 为拒绝操作设置Cookie保存状态 document.cookie = `cookieConsent=decline; max-age=${maxAge}`; } }); }); };
改动说明
- Cookie存储优化:用
cookieConsent字段存储用户明确选择,替代原模糊的cookieBy=SlavicMedia,便于后续精准判断 - 拒绝操作处理:新增对
declineBtn的逻辑处理,点击时设置对应Cookie,有效期与接受操作一致 - 逻辑判断优化:先检查是否存在选择记录Cookie,存在则根据值决定是否加载GA,且不再显示横幅;无记录时才展示提示框
内容的提问来源于stack exchange,提问作者Adam
相关产品推荐
相关产品推荐

