为何仅首页点击Cookie勾选框可全局设置Cookie,子页面不行?
Hey there, let's break down why your cookie consent is only working globally when you accept it on the homepage, and fix it up:
What's Going Wrong
The issue is that your setCookie function doesn't specify a path parameter for the cookie. By default, browsers set cookies to only be accessible from the current page's path:
- When you accept on the homepage (
/), the cookie gets a defaultpath=/, so every page on your site can read it. - When you accept on a subpage like
/kontakt/, the cookie is locked to/kontakt/—so other pages (including the homepage) can't see it, hence the popup keeps coming back.
The Fix
Update your setCookie function to explicitly add path=/—this makes the cookie accessible across your entire site:
function setCookie(cname, cvalue) { var d = new Date(); d.setTime(d.getTime() + (5*24*60*60*1000)); /* Quick note: your comment says "2 days" but this is 5 days—adjust if needed! */ var expires = "expires=" + d.toUTCString(); // Add path=/ to make the cookie site-wide document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/"; }
Bonus Improvements
I noticed a couple small things you might want to tweak too:
- Your
setCookieexpects two parameters, but you're only passing one when you call it (setCookie("MyPopUpCookie");). Adding a default value forcvalueavoids any weird edge cases:function setCookie(cname, cvalue = "accepted") { var d = new Date(); d.setTime(d.getTime() + (5*24*60*60*1000)); var expires = "expires=" + d.toUTCString(); document.cookie = `${cname}=${cvalue}; ${expires}; path=/`; } - For better security and compatibility, add the
SameSiteattribute to your cookie (most modern browsers expect this now):document.cookie = `${cname}=${cvalue}; ${expires}; path=/; SameSite=Lax`;
After making these changes, accepting the cookie on any page will set it for your entire site, and the popup won't reappear anywhere.
内容的提问来源于stack exchange,提问作者ania_piszko
相关产品推荐
相关产品推荐

