percy
percy

Reputation: 56

Cookie set using javascript disappears in IE 10 / IE 8 after some time

//http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
    var expires = "";
if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
            expires = "; expires="+date.toGMTString();
}
document.cookie = name+"="+value+expires+"; path=/";
}

I am trying to create cookie using the above function, on page load. And trying to observe cookie value using the below code in IE 10's the javascript console.

function setCookieAndTrack () {
    createCookie ('test', 'someValue', 99);
    var test = 0;
    setInterval(function () {
            console.log('document.cookie -- ', document.cookie, " - ", test++, " - ", (new Date()).getTime());
    }, 1000);
}

And then on body load calling the above function

<body onload="setCookieAndTrack();">

Here is the response I get when I am starting IE 10 fresh without any cached files.

document.cookie -- test=someValue - 0 - 1376957958770 
document.cookie -- test=someValue - 1 - 1376957959753 
document.cookie -- test=someValue - 2 - 1376957960751 
document.cookie -- test=someValue - 3 - 1376957961749 
document.cookie -- test=someValue - 4 - 1376957962747 
document.cookie -- test=someValue - 5 - 1376957963746 
document.cookie -- test=someValue - 6 - 1376957964760 
document.cookie --  - 7 - 1376957965744 
document.cookie --  - 8 - 1376957966757 
document.cookie --  - 9 - 1376957967755 
document.cookie --  - 10 - 1376957968769 
document.cookie --  - 11 - 1376957969752 
document.cookie --  - 12 - 1376957970766 
document.cookie --  - 13 - 1376957971764 
document.cookie --  - 14 - 1376957972747 
document.cookie --  - 15 - 1376957973761 

Thing is, this only happens when the browser starts fresh. After refreshing page, cookie value does not vanish.

I am using IE 10 (10.0.9200.16660) on Windows 7 (64-bit). I have also observed this with other IE versions.

Am I missing anything here?

Upvotes: 0

Views: 4027

Answers (1)

netpoetica
netpoetica

Reputation: 3425

Give this a go - try encoding the value and using UTCString instead. According to MDN, toUTCString should be used: https://developer.mozilla.org/en-US/docs/Web/API/document.cookie

It actually says GMT string in the docs, but then directs you to UTC.

function createCookie(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+"="+encodeURIComponent(value)+expires+"; path=/";
}

Upvotes: 3

Related Questions