jfc
jfc

Reputation: 397

Is it possible to set a cookie to expiry at the end of session and after 1 day?

I am using JavaScript cookies like in this guide here - https://www.w3schools.com/js/js_cookies.asp and have a cookie set up to expire on session.

Is it possible to also have it expire after 24 hours? So if the session is longer than 24 hours it will expire

Upvotes: 0

Views: 2705

Answers (1)

Tch
Tch

Reputation: 1055

the cookie will either expire on session end, or on a specific date, because in order to make the cookie expire on session end you actually omit the date to make it work.

unless you create 2 cookies one for session end and one on a date the function below is from the page you posted. use it to calculate the date and set the cookie where exdays=1. else just use the last line of the function omitting the expires so it can expire on session end

function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

Upvotes: 1

Related Questions