0

According to Set cookie and get cookie with JavaScript, the canonical function to set a cookie is:

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}

I'm trying to modify this function so that it:

a) instantiates a counter variable the first time the page loads

b) increments the counter variable each time the page is refreshed

c) prints the current value of the counter variable to the console

Here is my attempt:

function setCookie(name, value, days) {

    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    else {
        expires = "";
    }

    if (!value) {      // should I be checking to see if the COOKIE _itself_ exists? (rather than the value)
        var value = 1;
    } else {
        value++;
    }


    document.cookie = name + "=" + value + expires + "; path=/";
    console.log('Cookie value is', value)
}

### EDIT: ###

Here is a function to get the cookie:

function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

EDIT 2

Here is what I'm trying based on one of the suggestions:

function setCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
    console.log('Cookie value is', value)
}




function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}


//setCookie('foo', 3, 5);

//var x = readCookie('foo');

//if (x) {
//    console.log('this is foo bar!')
//}


let t = readCookie('foo') || 0;
setCookie('foo', t++, 5);

This results in:

Cookie value is 0

##########################################

Calling setCookie('test', 1, 5) results in:

Cookie value is 2

I get a value of 2 even when loading the page for the first time (presumably because there is a numerical value passed for value when the function is called).

Should I be checking to see if the cookie itself exists (rather than a numerical value for the value argument)?

I would greatly appreciate any assistance with implementing a, b, and c above.

Thanks!

equanimity
  • 2,371
  • 3
  • 29
  • 53
  • ... If you want to update the value of a cookie based on its previous value it's good to get the value from the cookie, and handle the case where there's no cookie to provide that value. – Dave Newton Nov 24 '21 at 00:44
  • yes, I don't think you need to modify the function at all. Just check for the cookie, and if it exists increment it. say you have a function getCookie(), then `let t = getCookie('test') || 0; setCookie('test', t++, days);` – Chris Strickland Nov 24 '21 at 01:20
  • @Dave Newton -- how do you get the value of the cookie from the cookie? (I'm new to cookie management and JavaScript) – equanimity Nov 24 '21 at 01:35
  • @Chris Strickland -- I am somewhat following you here. I have a `getCookie()` function (see edits above). Are you saying that I should pass back the `let t` into the setCookie() function? Thanks for clarifying. – equanimity Nov 24 '21 at 02:44
  • You just need to get the value that's already stored in your cookie. || is the OR operator. If getCookie returns a falselike value (undefined, null, 0, ''), then you'll get 0 out of that because js will follow chained booleans until it finds the first thing that evaluates to true. Then you increment the value you just got back and reset the cookie with the new value. So don't alter the setCookie function. You can even increment the value the same time as you pass it back to setCookie. It's not any extra steps, and it's actually a lot less code than what you have. – Chris Strickland Nov 24 '21 at 02:56
  • @ChrisStrickland -- I added an "EDIT2" above. Is this what you're suggesting? (if it is, the cookie value is 0 in the console, even if I continually reload the page... but this might have something to do with the fact that I'm accessing the page from `file:///C:/Users/me/Desktop/index.html)`. – equanimity Nov 24 '21 at 03:12
  • I don't think most browsers support cookies with the file:///protocol. Also, the stacks are sandboxed and won't let me set the cookies in a demo. You'll need to host this somewhere to test. I believe localhost is supported (with varying limitations depending on browser), so you don't actually have to push it to a server. – Chris Strickland Nov 24 '21 at 03:37

0 Answers0