22

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Learning
  • 1,171
  • 10
  • 20
  • 30

2 Answers2

69

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");
}
T.Todua
  • 53,146
  • 19
  • 236
  • 237
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • 1
    `expires` is obsolete, by the way. – Ry- May 23 '11 at 02:54
  • 2
    how do you expire a cookie if 'expires' is obsolete – aamiri Jan 24 '12 at 15:44
  • 7
    @aamiri The newer alternative is `max-age=numseconds` to expire the cookie `numseconds` after it was set. See the other answer here for usage. – Michael Berkowski Jan 24 '12 at 15:57
  • 1
    Doesn't really matter, but in sake of clarity I would use `> -1` rather than `>= 0`. – Silver Ringvee Apr 29 '16 at 07:53
  • @SilverRingvee Totally agree. The solution above doesn't work for Chrome – Michelangelo Jul 04 '16 at 21:41
  • @Michelangelo how for gods sake should >= 0 vs > -1 make that it is not working in chrome? – Eugene Nov 02 '16 at 22:52
  • @Eugene Don't know. I am not a browser developer. The above **answer** states to use >=0, i.e. equal or greater than zero. The only thing that worked in Chrome (few months ago) was to test if it was bigger than -1 for me. So I assume it was not sufficient to test if it was bigger than or equal to 0. Either way, totally agree to test for bigger than -1 to be sure, that was my point. – Michelangelo Nov 03 '16 at 13:20
  • 1
    the only **failure** of this method is if there is cookie with same name: **`blabla_visited`** – T.Todua Feb 14 '17 at 13:53
  • @MichaelBerkowski is the `=` supposed to be in `("visited=")` ? – Funk Forty Niner Jun 07 '17 at 13:20
  • @Fred-ii- I guess so. This sets the cookie value as `visited=yes`, so it was intended as a string match against the entire `Cookie:` header and could match with the `=` or without. I may have left it in just because the string `visited` might be more likely to occur in some other place in the cookie header and this needed to locate the string it explicitly set. – Michael Berkowski Jun 07 '17 at 13:46
  • @Fred-ii- Don't make me explain code from 6 years ago, man! ;) – Michael Berkowski Jun 07 '17 at 13:47
  • @MichaelBerkowski Haha! Ok thanks Michael. I'm just having this issue with cookies right now, which is something I haven't used in well over 10 years and given an XOR task; long story. I'm just not getting that thing to behave as it should. I've been at this for 3 solid days, believe it or not. But ..... persistance does (and hope) will pay off. Yet another "3 classic days on Google" *lol* – Funk Forty Niner Jun 07 '17 at 13:53
  • @MichaelBerkowski I think I may finally got my "Eureka" moment ;-) To which I used part of your code. Just wanted to say thanks, *cheers*. Now I have to tackle the next part of my "XOR" problem. *lol!* – Funk Forty Niner Jun 07 '17 at 14:04
  • @Fred-ii- Good luck! – Michael Berkowski Jun 07 '17 at 15:05
  • 1
    Thanks @MichaelBerkowski - Being persistant (which I am kind of a pitbull coder *lol!*) and debugging just paid off. Looking at HTML source (also), which many don't think of it as a debugging "tool", helped me to see where my JS was failing when pulled it in from an included PHP file and using cookies, which also needed to check if a file was empty or not, a real doozy of a project they wanted me to do. Now I can go on with the rest of my work; at long last. (Didn't meant to tie up comments here). – Funk Forty Niner Jun 07 '17 at 16:24
21
if (/(^|;)\s*visited=/.test(document.cookie)) {
    alert("Hello again!");
} else {
    document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
    alert("This is your first time!");
}

is one way to do it. Note that document.cookie is a magic property, so you don't have to worry about overwriting anything, either.

There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage and friends are convenient and useful.

Ry-
  • 218,210
  • 55
  • 464
  • 476