简体   繁体   中英

My Javascript cookie expires at session, not in 30 days

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"});
        }                   
});

This cookie expires when I shut down the browser, but I want it to last for 30 days until they see the popup again.

Instead of using expires , try max-age (in seconds). This doesn't involve the creation and modification of a Date instance.

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

Use the Cookie object:

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);
    }
};

Just use the below code to set your cookie:

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

Simple as that!

Also, to add 30 days to your date, you would have to do so:

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

since the time is in milliseconds and not in days.

A possible alternative is to use html5 localStorage. It's supported in IE8+ and doesn't have anything to do with sessions, so you won't be bit with any problems there. Here's how you might want to structure your code if you go the localStorage approach.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM