1. Tech

Your suggestion is on its way!

An email with a link to:


was emailed to:

Thanks for sharing About.com with others!

Reading Cookies

Join the Discussion

Questions? Comments?

More About Cookies

Writing Cookies Deleting Cookies

Knowing how to write cookies is only useful of we can read them back in at a later time. In this tutorial we are going to do just that.

Actually reading cookies is rather reasy in Javascript since all of the cookies that the page has access to are stored in document.cookie and so simply referencing that object gives us access to all of the cookies. It's not quitte that simple though because we probably want to access the value assigned to a specific cookie and so we need to find the cookie that we want within the cookie object.

The individual cookies are stored in the cookie object as a list of entries that are separated by a semi-colon and a space between each entry. Each entry in the list has the name of the cookie foloowed by equals followed by the value. Knowing this we can quickly convert our cookie object into an associative array of cookie values where each entry in the array has the same name as the cookie was given when it was written. The fillowing function will do this for us.

function loadCookies() {
var cr = []; if (document.cookie != '') {
  var ck = document.cookie.split('; ');
    for (var i=ck.length - 1; i>= 0; i--) {
      var cv = ck.split('=');
return cr;
var cookies = loadCookies();

This function returns our associative array of cookies when we call the function as shown in the last line of the above code. We can now test if a particular cookie exists by checking if an entry exists in the array by that name and if it does we can then retrieve its value. For example if we are looking for a cookie that we wrote using the name ''user", we could retrieve its value if it exists using::

if (cookie['user'] != null) user = cookie['user'];

This gives us the simplest possible way of being able to read any of the cookies that exist that our current page has access to. The only thing that you do have to remember if you work it this way is that any new cookies that you write will not be automatically added to the associative array when you write them. You probably wont need to read cookies in while still on the same page that you wrote them from since the original vale that you wrote to the cookie is still available. If you did you could always run the loadCookie() function again which would refresh the cookie array.

See More About

©2017 About.com. All rights reserved.