Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery cookie expiration value

Tags:

jquery

cookies

I have read a lot of jQuery cookie questions on here and know there is a jQuery cookie plugin (jQuery cookie). Without doing much investigation, the question: is there a way to determine expiration date of cookie?

From the 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/[email protected]
*/

Doesn't seem that this plugin can do it?

The reason I want to do this is that my cookie expires after 5 minutes of inactivity and Id like to notify user that their session is about to expire from Javascript.

like image 387
Chris Avatar asked Aug 05 '10 16:08

Chris


2 Answers

As it's not accessible from the JavaScript API, the only way is to store it in the content in parallel with the metadata.

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

Then read it back (obviously, add safeguards in case the cookie expired already) :

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

Note this will not be entirely reliable if the client clock changes in the meantime, say, due to DST.

like image 160
SF. Avatar answered Nov 04 '22 23:11

SF.


$.cookie("example", "foo", { expires: 7 });

Will expire in 7 days

there is no Javascript API that allows you to check the expiry date for a cookie

like image 22
Sotiris Avatar answered Nov 04 '22 21:11

Sotiris