jQuery cookie到期值

Chr*_*ris 7 cookies jquery

我在这里已经阅读了很多jQuery cookie问题,并且知道有一个jQuery cookie插件(jQuery cookie).没有做太多调查,问题是:有没有办法确定cookie的到期日期?

来自jquery.cookie doc:

/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
Run Code Online (Sandbox Code Playgroud)

这个插件似乎不能做到吗?

我想这样做的原因是我的cookie在5分钟不活动后过期,并且我想通知用户他们的会话即将从Javascript到期.

Sot*_*ris 6

$.cookie("example", "foo", { expires: 7 });
Run Code Online (Sandbox Code Playgroud)

将在7天后到期

没有允许您检查cookie的到期日期的Javascript API

  • 我想要到期值.我不是问如何设置到期值本身. (5认同)

SF.*_*SF. 5

由于无法通过JavaScript API进行访问,因此唯一的方法是将其与元数据并行存储在内容中。

  var textContent = "xxxx"
  var expireDays = 10;
  var now = new Date().getTime();
  var expireDate = now + (1000*60*60*24*expireDays);
  $.cookie("myCookie", '{"data": "'+ textContent +'", "expires": '+ expireDate +'}', { expires: expireDays  });
Run Code Online (Sandbox Code Playgroud)

然后将其读回(很明显,添加保护措施以防cookie过期):

var now = new Date().getTime();
var cookie = $.parseJSON($.cookie("myCookie"));
var timeleft = cookie.expires - now;
var cookieData = cookie.data;
Run Code Online (Sandbox Code Playgroud)

请注意,如果客户端时钟同时发生变化(例如由于DST),这将不是完全可靠的。


Nic*_*ver 3

除非发生了某些变化,否则您无法cookie 中获取该值,您可以设置它,但仅此而已,当它过期时,它就不会再出现在 cookie 集合中......但您看不到它例如,它会在 5 分钟后过期。

对于会话过期问题,最好的办法是使用setTimeout()正确的延迟,例如,如果是 5 分钟,您可能需要在 4 分 30 秒时发出警报,如下所示:

setTimeout(function() {
  alert("Your session will expire in 30 seconds!");
}, 270000);  //4.5 * 60 * 1000
Run Code Online (Sandbox Code Playgroud)