Learning Learning - 27 days ago 19
Javascript Question

Check if cookie exists else set cookie to Expire in 10 days

Here is what I'm looking to do (pseudo-code):

Imagine the name of the cookie in the example is "visited" and it contains nothing.

if visited exists
then alert("hello again");
else
create visited - should expire in 10 days;
alert("This is your first time!")


How can I achieve this in JavaScript?

Answer

You need to read and write document.cookie

if (document.cookie.indexOf("visited") >= 0) {
  // They've been here before.
  alert("hello again");
}
else {
  // set a new cookie
  expiry = new Date();
  expiry.setTime(expiry.getTime()+(10*60*1000)); // Ten minutes

  // Date()'s toGMTSting() method will format the date correctly for a cookie
  document.cookie = "visited=yes; expires=" + expiry.toGMTString();
  alert("this is your first time");
}
Comments