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

时间:2011-05-23 02:16:52

标签: javascript cookies

以下是我要做的事情(伪代码):

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

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

如何在JavaScript中实现这一目标?

2 个答案:

答案 0 :(得分:66)

您需要阅读和撰写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");
}

答案 1 :(得分: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!");
}

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

还有more convenient libraries to work with cookies,如果您不需要在每次请求时发送到服务器的信息,HTML5’s localStorage and friends便捷且有用。