我试图为我的网站设置一个cookie,它将在3分钟内过期,但没有运气......所以我发现了30天内到期的代码,但工作完美但我还是很难将其设置为3分钟。
/**
* JS script with cookie integration for redirecting visitors to a splash page. jQuery free.
*
* @author Tyler Pearson
* @version 1.0
*/
var NMC = NMC || {};
NMC.Splash = (function () {
"use strict";
var daysBeforeCookieExpires = 30, //Need to change it for 3 min!!!
createCookie = function(name, value, expires, path, domain) {
var cookie = name + "=" + escape(value) + ";";
if (expires) {
if (expires instanceof Date) {
if (isNaN(expires.getTime())) {
expires = new Date();
}
} else {
expires = new Date(new Date().getTime() + parseInt(expires, 10) * 1000 * 60 * 60 * 24);
}
cookie += "expires=" + expires.toGMTString() + ";";
}
if (path) {
cookie += "path=" + path + ";";
}
if (domain) {
cookie += "domain=" + domain + ";";
}
document.cookie = cookie;
},
getCookie = function(name) {
var regexp = new RegExp("(?:^" + name + "|;\\s*" + name + ")=(.*?)(?:;|$)", "g"),
result = regexp.exec(document.cookie);
return (result === null) ? null : result[1];
},
readCookie = function(name) {
var nameEQ = name + "=",
ca = document.cookie.split(';'),
i,
c;
for (i = 0; i < ca.length; i += 1) {
c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length, c.length);
}
}
return null;
};
return {
baseSetup: function(cookieName, splashURL) {
if (!(getCookie(cookieName))) {
createCookie("_splash-entrance", window.location.pathname, daysBeforeCookieExpires);
window.location = splashURL;
}
},
splashSetup: function(cookieName, expiresInDays) {
if (expiresInDays) {
daysBeforeCookieExpires = expiresInDays;
}
var link = document.getElementById('splash-continue');
createCookie(cookieName, true, daysBeforeCookieExpires);
if (!(readCookie("_splash-entrance") === null)) {
link.href = readCookie("_splash-entrance");
} else {
link.href = "/";
}
}
};
}());
答案 0 :(得分:0)
在这里看看这个答案: How do I set a cookie to expire after 1 minute or 30 seconds in Jquery?
以下是使用jQuery cookie插件设置为3分钟的cookie示例:
var date = new Date();
date.setTime(date.getTime() + (60 * 3000));
$.cookie('username', username, { expires: date }); // expires after 3 minutes
插件: https://github.com/carhartl/jquery-cookie
检查插件的使用情况。这应该让你开始。