'How can I find out what's changing a cookie value?

I have a small piece of javascript code that seems to be getting overridden somewhere and I can't trace where.

This snippet of javascript writes a cookie value and logs both the input value, and the resulting cookie value:

function cookieSet(name, val) {
    const expDays = 365;
    let d = new Date();
    d.setTime(d.getTime() + (expDays * 24 * 60 * 60 * 1000));
    let expiry = "expires="+d.toUTCString();
console.log('val:');
console.log(val);
    document.cookie = name + "=" + val + ";" + expiry;
}

function cookieGet(cName) {
    let name = cName + "=";
    let ca = document.cookie.split(';');
    let rVal = '';
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') { c = c.substring(1); }
        if (c.indexOf(name) == 0) {
console.log(c);
            rVal = c.substring(name.length, c.length);
            break;
        }
    }
    return rVal;
}

function test() {
    let val = 0;
    console.log(val);               
    cookieSet('test', val);
    console.log(cookieGet('test'));
}

test();

When I run it, all console.log lines output 0 as the value, including the line that logs the output of cookieGet('test') after setting the cookie — so far so good.

But then if I run cookieGet('test') somewhere later in the code or even manually in the console, the output is 1.

What's more, if I manually check the cookie within the browser's developer console, it also reports that the cookie was set as 1, even though the log lines all indicate it was set as 0.

My first assumption was the value must be getting set somewhere else after it's set in the test() function, but if I remove the cookieSet() line from the test() function and watch the cookies in the developer console, the value doesn't get set at all when the script runs.

So it doesn't seem to be getting set anywhere else other than in the test() function, and the test() function always logs the value when it's being set. When the script runs I only see the logging for the value being set as 0, there's no logging of the value being set as 1.

It seems like something is mysteriously changing the value somewhere after the console.log(cookieGet('test')) line, but there's literally nothing else in the code that interacts with the cookie other than calling cookieGet() to read it, so I'm not sure where else to look.

The log line in the cookieSet() function outputs the full cookie string, and it outputs "test=0" when running as part of the script, but after the script has run, if I run cookieGet('test') in the console, the output for that line is "test=1". So it doesn't seem to be a problem with interpreting the cookie value from the cookie string, the actual value is indeed being set wrong somewhere.

How do I find out what's going on here??



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source