0

I'm running into an issue getting a cookie to store. The code below works for it's intended purpose. Which is to save just the first.last name put in, user has to put joe.smith not joe then smith. The cookie saves which is good, but after the browser is closed it removes the cookie. I know somehow i have to give an expiration date to it, but I can't seem to figure it out. What would be straightforward way of adding the expiration date to be permanent?

 <!DOCTYPE html>
<html>

<script>
function writeCookie(){
if(document.cookie === "")
{

document.cookie = prompt("Enter first.last name: ");

}
}
writeCookie();
var name = document.cookie;
document.write("Your name is: ");
document.write(name);
</script>

</body>

</html>
aaro grill
  • 19
  • 4

2 Answers2

1

If neither expires nor max-age specified it will expire at the end of session.

document.cookie is just a string and you can modify it as you would any other sting.

function writeCookie(){
    if(document.cookie === ""){
        document.cookie = prompt("Enter first.last name: ");
        document.cookie = document.cookie + ';max-age=' + (24*60*60*1000) // one day
    }
}
writeCookie();
var name = document.cookie;
document.write("Your name is: ");
document.write(name);

Ref: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

vatz88
  • 2,422
  • 2
  • 14
  • 25
0

By default cookies will exist only as long as your browser is open unless you explicitly set an expiry.

Cookies have name-value pairs. Ideally your cookie should be in a format something like this:

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";

Here the value for username is John Doe and the expiry date is the next part. You could use document.cookie.split(";") to split the string into the first part and second part. Then for each part you can further split to get each value. You can read more about the manipulation and reading of cookies here: https://www.w3schools.com/js/js_cookies.asp

In you case, a straight forward way to add an expiration to an existing cookie would be using something like the function below. Here the 'exdays' variable is how many days(Starting from the current day) you want the cookie to exist for:

function setCookieExpiry(exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires="+ d.toUTCString();
  document.cookie = document.cookie "; " + expires;
}

I have not tested this code, so please comment if it does not work and I'll look at it again.

Winston Jude
  • 569
  • 2
  • 11