Cookies
Cookies copied to clipboard
How can i update a cookie without resetting its expiry date
I want to be able to set an expiry date to the cookie and add some data to that cookie on certain events without resetting the expiry of it .. how can that be achieved using this library?
This is what I used in case someone is stuck at this point.. Please feel free to edit my solution .. or suggest other ones too.. And please support updating the cookie in this library as a request
// Helper function to set how many days to expire the cookie
setExpiry = function(days){
var minute = 60,
second = 60,
day=24,
ms = days * day * minute * second,
date = new Date();
date.setTime(date.getTime()+(ms *1000));
return { ms: ms, date: date.toUTCString()};
}
// use this function to set a cookie or override it .. note that this will override the expiry date
setCookie = function(name,data,expiry) {
if(expiry){
// resetting the cookie
Cookie.setJSON(name, {data: data, expires: this.setExpiry(expiry).date}, { expires: this.setExpiry(expiry).ms});
return;
}
// no expiry date
Cookie.setJSON(name, data);
}
// use this function to update a cookie keeping the same expiry date
updateCookie = function(name, data){
if(this.getCookie(name)){
var getCookie = this.getCookie(name);
var today = new Date();
var expiryDate = new Date(this.getCookie(name).expires);
var timeDiff = Math.abs(today.getTime() - expiryDate.getTime());
daysLeft = Math.ceil(timeDiff / (1000 * 3600 * 24));
this.setCookie(name, data, daysLeft);
return;
}
console.error('Update Failed! Cookie {'+ name +'} doesnt exist.');
}