解决Cookie Consent Banner用户同意后刷新/跳转重新显示问题
你的核心问题是页面加载时没有检查用户是否已经做出过Cookie同意/拒绝的选择,导致每次刷新或跳转都会重新渲染横幅。另外当前的JS逻辑存在重复绑定点击事件、拒绝操作未记录Cookie的问题,下面是完整修复方案:
一、页面初始化时检查Cookie状态,控制横幅显示
在页面加载完成后,先判断是否存在用户的Cookie选择记录,以此决定是否显示横幅:
$(document).ready(function() { const consentCookie = Cookies.get('CUSTOM_COOKIE'); const cookieBanner = $('#cookie-banner'); // 用户已做出选择(同意/拒绝),直接隐藏横幅 if (consentCookie === 'true' || consentCookie === 'false') { cookieBanner.hide(); // 若为同意状态,同步更新GA/GTM的授权状态 if (consentCookie === 'true') { gtag('consent', 'update', { 'ad_storage': 'granted', 'analytics_storage': 'granted' }); } } else { // 无选择记录,显示横幅 cookieBanner.show(); } });
二、修正同意按钮逻辑(消除重复绑定)
当前consentGranted函数内重复绑定点击事件,和按钮上的onclick冲突,改成直接在触发时完成所有操作:
function consentGranted() { const cookieBanner = $('#cookie-banner'); // 存储同意状态Cookie,有效期365天 Cookies.set('CUSTOM_COOKIE', 'true', { expires: 365 }); // 更新GA/GTM授权状态 gtag('consent', 'update', { 'ad_storage': 'granted', 'analytics_storage': 'granted' }); // 隐藏横幅 cookieBanner.hide(); }
三、修正拒绝按钮逻辑(添加拒绝状态记录)
原拒绝操作仅隐藏横幅,未记录状态,导致刷新后横幅重现,需添加拒绝状态的Cookie:
function dismissCookieBanner() { const cookieBanner = $('#cookie-banner'); // 存储拒绝状态Cookie,有效期365天 Cookies.set('CUSTOM_COOKIE', 'false', { expires: 365 }); // 更新GA/GTM授权状态 gtag('consent', 'update', { 'ad_storage': 'denied', 'analytics_storage': 'denied' }); // 隐藏横幅 cookieBanner.hide(); }
四、优化HEAD中的GTM/GA脚本(消除重复定义)
原HEAD内重复定义dataLayer和gtag函数,改成单次定义:
<head> <!-- Cookie Consent Banner --> <script> window.dataLayer = window.dataLayer || []; function gtag() {dataLayer.push(arguments);} // 默认拒绝所有存储授权 gtag('consent', 'default', { 'ad_storage': 'denied', 'analytics_storage': 'denied' }); </script> <script async src="https://www.googletagmanager.com/gtag/js?id=TAG_ID"></script> <script> gtag('js', new Date()); gtag('config', 'TAG_ID'); </script> <script> function consentGranted() { gtag('consent', 'update', { 'ad_storage': 'granted', 'analytics_storage': 'granted' }); } function dismissCookieBanner() { gtag('consent', 'update', { 'ad_storage': 'denied', 'analytics_storage': 'denied' }); } </script> <!-- Cookie Consent Banner --> </head>
修改完成后,用户首次访问会显示横幅,点击同意/拒绝后会记录Cookie状态;后续刷新或跳转页面时,页面初始化会自动读取Cookie并隐藏横幅,同时同步GA/GTM的授权状态,完全符合需求。
内容的提问来源于stack exchange,提问作者curiousbean
相关产品推荐
相关产品推荐

