Orthogonal Thought | Random musings from the creator of Cooking For Engineers and Lead Architect of Fanpop

AUTHORS

CATEGORIES

ARCHIVE

Accessing and Reading Cookies in JavaScript correctly

Posted 25 June, 2009 at 5:25pm by Michael Chu
(Filed under: Web 2.0)

Recently, I've had to deal with web browser cookies a lot, and, in one case, I had to read several cookies using JavaScript. I looked up how to read cookies and JavaScript and found out there's no built in function that parses out the value of a particular cookie key - you have to write your own function or copy an already written one. I grabbed one from a popular website that provides HTML and JavaScript lessons and tutorials, but then discovered that it was providing the wrong cookie value for this one particular cookie I was trying to read. I tried another function from another website and same problem.

The cookie I was trying to read started with the same name as part of the name of another cookie already set. For example, I was looking for "targetcookie" but an earlier cookie of the name of "the_wrong_targetcookie" exists. I got the value of "the_wrong_targetcookie" instead. I looked at the functions I had grabbed and it was pretty easy to see that the string searching implemented was too simplistic to work in all cases. (Another solution could have been to change the cookie names, but I wasn't the one setting the cookies. The API I was working with dictates the cookie names and both cookies were set by that API.)

I wrote this simple function instead:

function getCookie(cookie_name)
{
	if (document.cookie && document.cookie.length>0)
	{
		cookie_index = document.cookie.indexOf(cookie_name+"=");
		if (cookie_index != 0) cookie_index = document.cookie.indexOf(" "+cookie_name+"=");
		if (cookie_index != -1)
		{
			cookie_start=document.cookie.indexOf("=",cookie_index)+1;
			cookie_end=document.cookie.indexOf(";",cookie_start);
			if (cookie_end==-1) cookie_end=document.cookie.length;
			return unescape(document.cookie.substring(cookie_start,cookie_end));
		}
	}
	return "";
}

Feel free to copy this function for your own use (just leave me a note if you found it useful). If you find something wrong with it, let me know, and I'll try to fix it.

NAVIGATION

SEARCH