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

Lea*_*ing 22 javascript cookies

这是我要做的(伪代码):

想象一下,示例中cookie的名称是"已访问",并且它不包含任何内容.

if visited exists
then alert("hello again");
else
create visited - should expire in 10 days;
alert("This is your first time!")
Run Code Online (Sandbox Code Playgroud)

我怎样才能在JavaScript中实现这一目标?

Mic*_*ski 68

你需要读写 document.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");
}
Run Code Online (Sandbox Code Playgroud)

  • @aamiri更新的替代方法是`max-age = numseconds`,以便在设置后使cookie"numseconds"失效.请参阅此处的其他答案以供使用. (7认同)
  • 如果“过期”已过时,如何使cookie过期 (2认同)

Ry-*_*Ry- 21

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!");
}
Run Code Online (Sandbox Code Playgroud)

是一种方法.请注意,这document.cookie是一个神奇的属性,因此您也不必担心覆盖任何内容.

还有更方便的库来处理cookie,如果您不需要在每次请求时发送到服务器的信息,HTML5 localStorage和朋友都很方便实用.

  • Chrome修复:`/(^ |;\s?)访问= /` (3认同)