我的 Javascript cookie 在会话时过期,而不是在 30 天后过期

My Javascript cookie expires at session, not in 30 days

本文关键字:过期 天后 Javascript 会话 我的 cookie      更新时间:2023-09-26
jQuery(document).ready(function(){
        if (document.cookie.indexOf('visited=true') === -1) {
            var expires = new Date();
            expires.setDate(expires.getDate()+30);
            document.cookie = "visited=true; path=/; expires="+expires.toUTCString();
            jQuery.colorbox({open:true,href:"<?=home_url()?>/popup/?site_type=2",iframe:true, innerWidth:"700px", innerHeight:"410px"});
        }                   
});

当我关闭浏览器时,此cookie会过期,但我希望它持续30天,直到他们再次看到弹出窗口。

不要使用 expires ,请尝试max-age(以秒为单位)。这不涉及创建和修改Date实例。

if (document.cookie.indexOf('visited=true') === -1) {
    document.cookie = "visited=true; path=/; max-age=2592000;";

使用 Cookie 对象:

var CookieExpiryTime = {
    END_OF_SESSION : 0,
    SECOND : 1000,
    MINUTE : 1000 * 60,
    HOUR : 1000 * 60 * 60,
    DAY : 1000 * 60 * 60 * 24,
    YEAR : 1000 * 60 * 60 * 24 * 365,
    NEVER : 1000 * 60 * 60 * 24 * 365 * 20
}
var Cookie = {
    Set: function (n, v, time, path) {
        var e = '', d;
        if (time) {
            d = new Date();
            d.setTime(d.getTime() + (time));
            e = "; expires=" + d.toGMTString();
        }
        if (!path) path = "/";
        document.cookie = n + "=" + v + e + "; path="+path;
    },
    Get: function (n) {
        var match = n + "=", c = '', ca = document.cookie.split(';'), i;
        for (i = 0; i < ca.length; i++) {
            c=String(ca[i]).trim()
            if (c.indexOf(match) === 0) {
                return c.substring(match.length, c.length);
            }
        }
        return null;
    },
    Unset: function (n) {
        this.Set(n, "", -1);
    }
};

只需使用以下代码来设置您的 cookie:

Cookie.Set("visited", "true", CookieExpiryTime.MONTH);

就这么简单!

此外,要为您的日期添加 30 天,您必须这样做:

expires.setDate(expires.getDate()+30*24*60*60*1000);

因为时间是以毫秒为单位而不是以天为单位。

一种可能的替代方案是使用 html5 localStorage。它在IE8 +中受支持,并且与会话没有任何关系,因此您不会遇到任何问题。以下是采用 localStorage 方法时可能希望如何构建代码。

var 30_DAYS = 1000 * 60 * 60 * 24 * 30;
var msgSent = localStorage.msgSent;
var now = new Date().getTime();
var diff = now - msgSent;
if (!msgSent || msgSent > 30_DAYS) {
  sendMsg();
}
function sendMsg() {
 // do your popup thing
 localStorage.msgSent = new Date.getTime();
}