Javascript 检查cookie是否存在,否则将cookie设置为在10天内过期

Javascript 检查cookie是否存在,否则将cookie设置为在10天内过期,javascript,cookies,Javascript,Cookies,下面是我要做的(伪代码): 假设示例中cookie的名称为“visted”,但它不包含任何内容 if visited exists then alert("hello again"); else create visited - should expire in 10 days; alert("This is your first time!") 如何在JavaScript中实现这一点 if (/(^|;)\s*visited=/.test(document.cookie)) { al

下面是我要做的(伪代码):

假设示例中cookie的名称为“visted”,但它不包含任何内容

if visited exists
then alert("hello again");
else
create visited - should expire in 10 days;
alert("This is your first time!")
如何在JavaScript中实现这一点

if (/(^|;)\s*visited=/.test(document.cookie)) {
    alert("Hello again!");
} else {
    document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
    alert("This is your first time!");
}
这是一种方法。请注意,
document.cookie
是一个神奇的属性,因此您也不必担心覆盖任何内容


此外,如果您不需要每次请求时发送到服务器的存储信息,这些信息也非常方便和有用。

您需要读写
文档。cookie

if (document.cookie.indexOf("visited=") >= 0) {
  // They've been here before.
  alert("hello again");
}
else {
  // set a new cookie
  expiry = new Date();
  expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes

  // Date()'s toGMTSting() method will format the date correctly for a cookie
  document.cookie = "visited=yes; expires=" + expiry.toGMTString();
  alert("this is your first time");
}

expires
是过时的,顺便问一下。如果“expires”是过期的,您如何使cookie过期obsolete@aamiri较新的替代方法是
max age=numseconds
在cookie设置后使其过期。有关用法,请参见此处的另一个答案。这并不重要,但为了清楚起见,我会使用
-1
而不是
=0
。此方法唯一的失败是如果存在同名cookie:
blablabla_visted
Chrome fix:
/(^ |;\s?)visted=/code>