An Introduction to saving, reading, and using JavaScript Cookies

Javascript Cookies are variables that are stored on the visiting users computer. These cookies are unique to a domain so that if the site www.example.com sets a cookie with information in it that cookie can not be read and utilized by www.xyz.com. In most cases cookies are used to save user settings for your website, when they last logged in, etc. However they should not be used to store sensitive information as the cookie information is transferred with each page request to the server.

With that out of the way lets get right into things, and understand the 3 things that define your cookie value.

  • Name: The name to identify your cookie
  • Value: The value to be stored in the cookie
  • Expiration Date: When does this cookie value expire

The cookie is set and read by using JavaScript and in particular the document.cookie element of the DOM. You set a cookie by setting document.cookie to your desired name-value pair and expiration date with the format of “name=value; expires=date;”. For example if we wanted to define a cookie with the property user and set it to abc123 with an expiration day of March 3sst document.cookie =’user=abc123; expires=Wed, 31 Mar 2010 20:47:11 UTC;

To access the saved cookie we would read out the value of document.cookie. This property returns a string representation of all the name-value properties that have been set to the cookie. Therefore you will need to parse the returned String to get your desired value. The easiest way to do this is to get the indexOf method to get the starting point of the property value and get the value up to the next semi-colon or end of the string if one doesn’t exist.

To help illustrate lets assume I have set a cookie with user = abc123 and settings = Show All. If a cookie was set with these properties then document.cookie would return the following.

user=abc123; settings=Show All

Therefore to get the user property you would need to get the index of user= and return the string from that index plus its length until the next ; or end of the cookie value if user was the last property.

start_idx=document.cookie.indexOf("user=");
cookie_value = "";
if (start_idx != -1)
{
    start_idx=start_idx+ 6;
    end_idx=document.cookie.indexOf(";" , start_idx);
    if (end_idx == -1) {
        end_idx = document.cookie.length;
    }
    cookie_value = document.cookie.substring(start_idx, end_idx);
}
alert(cookie_value);

To make things easy on yourself, there are a lot of existing functions and libraries that have defined methods for reading and writing cookies. W3Schools has an excellent set of functions at www.w3schools.com/JS/js_cookies.asp. In addition many JavaScript libraries either have built in cookie support or plugins for handling them.

// HTML/CSS // Javascript //

Comments & Questions

Add Your Comment