Browser Cookies with JavaScript

Using JavaScript to set and get cookies is pretty straightforward. I wrote a simple function to set cookies for a game I’m working on. This code initializes/resets the cookies.


var cookie_days = 30;
var cor = 0;
var inc = 0;
var screen = 0;
var level = "MW1";
setCookie('VPA_cor',cor,'N');
setCookie('VPA_inc',inc,'N');
setCookie('VPA_screen',screen,'N');
setCookie('VPA_level',level,'Y');

function setCookie(cname, cvalue, set_time) {
var expires = '';
if ( set_time == 'Y' ) {
    var d = new Date();
    d.setTime(d.getTime() + (cookie_days*24*60*60*1000));
    expires = "expires="+d.toUTCString();
}
//alert('cname ' + cname + 'group ' + cvalue + 'time ' + expires);
document.cookie = cname + "=" + cvalue + "; " + expires;
}

Note that the JavaScript code for setting and resetting a cookie is the same. One caveat is that if the cookie has been set outside of JavaScript, e.g. in PHP, then it is possible that the httponly has been set to TRUE. In that case you cannot modify an existing cookie with JavaScript.

You can get the value of the cookies with this code.


var cookie_name = 'VPA_cor';
var cor = retrieve_cookie(cookie_name);

In my code, I set the cookies with PHP, so the path is already set. If you initialize a cookie with JavaScript, you can set the path by adding a path parameter.


 document.cookie = name + '=' + value + ';' +
                   'expires=' + expires + ';' +
                   'path=' + path + ';';

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.