添加Cookie到期日期

时间:2019-05-29 20:14:24

标签: javascript cookies

我在SOF上找到了这个javascript cookie脚本,它确实满足我的要求。将首次访问者重定向到其他URL。我只希望它的有效期为1天。

if (getCookie("first_visit") != "true") {
document.cookie = "first_visit=true";
location.href="http://pgklavertjevier.nl";    
}

function getCookie(cname) {
var name = cname + "=";
   var ca = document.cookie.split(';');
      for(var i = 0; i <ca.length; i++) {
         var c = ca[i];
         while (c.charAt(0)==' ') {
            c = c.substring(1);
         }
         if (c.indexOf(name) == 0) {
            return c.substring(name.length,c.length);
         }
     }
    return "";
}

1 个答案:

答案 0 :(得分:1)

您可以在创建cookie时设置cookie的失效日期(以您的情况为1天)及其值。

如果要通过javascript创建cookie,则可以使用以下代码:

function setCookie(name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()) + ";path=/";
    document.cookie = name + "=" + c_value;
}

setCookie("first_visit", true, 1);