【问题标题】:JavaScript function detects cookie set during session, but not a pre-existing cookie at start of new sessionJavaScript 函数检测会话期间设置的 cookie,但在新会话开始时检测不到预先存在的 cookie
【发布时间】:2021-08-16 16:31:35
【问题描述】:

函数调用 cookieExists('stylesheet') 应该检测 cookie 的存在,如果存在名为“stylesheet”的 cookie,则返回 true,否则返回 false。

function cookieExists(name) {
   var ckArr = document.cookie.split(';');
   for(i = 0; i < ckArr.length; i++)
   if (ckArr[i].split('=')[0].trim() == name) return true;
   else return false;
}

此功能旨在检查所有现有 cookie 的名称,但我在一个只有一个 cookie 的页面上使用它 - 它的名称是“样式表”。我在页面加载时调用它来检查名为“样式表”的 cookie 是否存在。此 cookie 指定上次使用的 CSS 文件(用户可以选择任一样式表):样式表 1.css 或样式表 2.css。如果存在名为 'stylesheet' 的 cookie,我想使用 cookie 中指定的样式表来显示页面。

现在,如果实际上没有名为“样式表”的现有 cookie,cookieExists('stylesheet') 会返回 false。如果我在页面中添加一个名为“样式表”的 cookie,cookieExists('stylesheet') 返回 true。到目前为止,一切顺利。

但是,如果我随后关闭浏览器选项卡 - 虽然页面上附加了名为“样式表”的 cookie - 然后在新选项卡中打开同一页面,cookieExists('stylesheet') 不再检测到 cookie 并返回 false! cookie 仍然附加到页面 - 在上一个会话结束时它还没有过期。

需要明确的是,我在页面加载时使用window.onload = findStylesheet; 调用cookieExists('stylesheet'),其中函数findStylesheet() 调用cookieExists('stylesheet')

function findStylesheet() {
  let savedStylesheet = cookieExists('stylesheet');
  if (savedStylesheet) {
    let setStylesheet = Cookies.get('stylesheet');
    let newStylesheet = document.getElementById("stylesheet");
    newStylesheet.setAttribute('href', setStylesheet);
   }
}

函数Cookies.get('stylesheet') 是一个js-cookie 函数。

如果有人能指出我哪里出错了,我将不胜感激。

【问题讨论】:

    标签: javascript cookies


    【解决方案1】:

    已解决 - 我一直在离线工作。当我将相关页面放到网上时,一切正常。所以我在那里学到了一些东西。

    让我感兴趣的是 cookie 在 Firefox 中离线“工作”。我可以设置、更新和读取 cookie。我只是无法在新会话开始时读取上一个会话中存在的 cookie。但是,对于 Chrome,没有任何效果。

    感谢 Alias C 的想法。

    【讨论】:

      【解决方案2】:

      您是否尝试将过期属性添加到您的Cookies.set()?在使用您的代码进行测试后,我认为这可能是一个问题,另一个是您的 cookieExists 函数不适用于我的其他代码找到的 cookie,因此这可能是另一个问题。我将 findStylesheet 函数更改为:

      function findStylesheet() {
        let savedStylesheet = Cookies.get('stylesheet');
        if (savedStylesheet) {
          let newStylesheet = document.getElementById("stylesheet");
          newStylesheet.setAttribute('href', setStylesheet);
          return true;
         }
        return false;
      }
      

      我还使用了一种测试方法来检查 cookie:Cookies.set('stylesheet', 'path-to-stylesheet',{ expires: 365 });(注意括号中的 expires)。这段代码对我有用,当我关闭并打开浏览器时,cookie 仍然存在,但是,如果我忽略过期时间,则找不到 cookie。

      【讨论】:

      • 感谢您的回答。是的,我的 cookie 有一个过期日期 - 它没有过期。在浏览器控制台中验证。我同意函数cookieExists 不好。我也试过函数getCookielink,得到了同样的结果!您的函数Cookies.set 似乎缺少它的价值。但是,我没有在 my Cookies.set 中指定路径。我已经开始使用 w3schools 的功能(它们包括路径 - 见上面的链接),但我得到了相同的结果。这些结果是使用 Firefox 的;刚刚用 Chrome 尝试过 - 甚至无法设置 cookie!
      • 另一种可能性是环境。当我尝试在非托管页面(甚至 jsfiddle)中设置 cookie 时,它​​根本不起作用。您可能需要设置不同的主机环境来检查它是否正常工作,或者尝试改用localstorage
      猜你喜欢
      • 2010-11-26
      • 2011-12-09
      • 2012-04-22
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2013-11-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多