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=/";
}
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.
Comments
Post a Comment