How do you set a cookie to persist after closing the browser window using JavaScript?

 To set a cookie in JavaScript that will persist after the browser window is closed, you can use the `setCookie` function with a specific expiration date. Here's an example of how to set a cookie named "username" with the value "JohnDoe" that expires in 30 days:

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=/";

}

setCookie("username", "JohnDoe", 30);


In this example, the setCookie function takes three parameters: the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until the cookie expires (exdays). The function uses the JavaScript Date object to set the expiration date, which is set to the current date plus the number of days specified by the exdays parameter. The cookie is then set by assigning the concatenation of the cname, cvalue, expires and ';path=/' to the document.cookie property.

You can also set the expiration time in seconds instead of days:

function setCookie(cname, cvalue, exseconds) {
  var d = new Date();
  d.setTime(d.getTime() + (exseconds*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
setCookie("username", "JohnDoe", 86400*30);

It's worth noting that cookies are stored on the client side, so it's important to keep in mind that cookies can be deleted, modified, or blocked by the user at any time, so it's important to handle the cases when cookies are not available in the application.





Comments

Popular Posts