【问题标题】:Check if cookie exists else set cookie to Expire in 10 days检查 cookie 是否存在,否则将 cookie 设置为 10 天内过期
【发布时间】:2011-08-30 20:05:20
【问题描述】:

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

假设示例中的 cookie 的名称是“已访问”并且它什么都不包含。

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

如何在 JavaScript 中实现这一点?

【问题讨论】:

    标签: javascript cookies


    【解决方案1】:

    你需要读写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");
    }
    

    【讨论】:

    • 顺便说一句,expires 已经过时了。
    • 如果 'expires' 已过时,如何使 cookie 过期
    • @aamiri 较新的替代方案是 max-age=numseconds 以在设置 cookie numseconds 后使其过期。有关用法,请参见此处的其他答案。
    • 没关系,但为了清楚起见,我会使用> -1 而不是>= 0
    • 这个方法唯一的失败是如果有同名的cookie:blabla_visited
    【解决方案2】:
    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 既方便又有用。

    【讨论】:

    • Chrome 修复:/(^|;\s?)visited=/
    猜你喜欢
    • 1970-01-01
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多