You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何仅首页点击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 default path=/, 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 setCookie expects two parameters, but you're only passing one when you call it (setCookie("MyPopUpCookie");). Adding a default value for cvalue avoids 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 SameSite attribute 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:07:54