September 7, 2006

Javascript Cookies

Filed under: Javascript — chris @ 9:21 pm

Using a cookie with JavaScript is easy. With the cookie, you can save small bits of information that will allow you to create a customized experience for the user. Remember though, you should never save personal information in a cookie, like a social security number, a password, or a credit card number. Cookies are not a very secure way of transferring information. Also, don’t rely too heavily on JavaScript cookies since a viewer can turn them off. If you need to track viewer information or pass personal information, use server-side session variables.

How To Set a Cookie

JavaScript has a built in object called the “cookie” object. You can access it simply with the following call.

alert(document.cookie)

Click Here to see what is in your browsers doument.cookie.

If you want to save something as a cookie, you have to URL encode it. This means you should use the same syntax that you see when people pass information in the address bar of a web address (the GET method, to be exact.) For example, www.chickenbeak.com?site=chickenbeak or www.chickenbeak.com?name=chris&site=chicken.

document.cookie = "site=chickenbeak"
document.cookie = "name=chris"

Click Here to set your browsers cookie like above.
Then Click Here to see what is in your browsers doument.cookie.

As you can see, the cookies are stored in the same format that you write them as, which is again URL encoded. You will want a JavaScript function that sifts through the document.cookie object and picks out the information you need. We will do this by splitting the long string saved in the document.cookie, and take the one bit of info we need.

What if we wanted to display a JavaScript message box to a visitor the first time they visit your homepage, but not every time they browse back to your homepage from a sub page of the site. We will set a cookie telling us that they have been there. Let’s start with a JavaScript function.

function getCookie(cookieName) {}

The way we want this function to work is to pass the function a cookie name, and it returns the cookie value. We will mainly be using the JavaScript “split” function, storing the separate values into an array, and for each spot in that array running the split again. See, this is the pattern of a long cookie.

“varName=varValue;varName=varValue;varName=varValue”

So, let’s do the first split.

cookieInfo = document.cookie
cookieInfo = cookieInfo.split(";")

This leaves us with an array “cookieInfo” which would contain values looking like “varName=varValue” for each cookie. We need to loop through this array one time and split it again.

cookieCount = cookieInfo.length
for(i = 0; i < cookieCount; i++) {
tempCookieInfo = cookieInfo[i].split("=")
//next we look at the [0] spot, which is the "varName"
//and look to see if it match's the "cookieName"
if(unescape(tempCookieInfo[0]) == cookieName
return tempCookieInfo[1]
}
}

Note the comment above in the code. That is where we get the actual value based on the name of the cookie. Notice the use of the “unescape” JavaScript function? Remember that the cookies are URL encoded, which means you’ll get the codes like %20 instead of a space. That unescape will help in keeping the information formatted best for your JavaScript comparisons.

Let’s put it all together

We have a function now that will pull a value out of the document.cookie object. We would use it something like this…

if(getCookie("mySiteVisited") == "yes") {
//do nothing
} else {
document.cookie = "mySiteVisited=yes"
alert("Welcome!")
}

And that would of course require our full function from above…

function getCookie(cookieName) {
if(document.cookie) {
cookieInfo = document.cookie
cookieInfo = cookieInfo.split(";")
cookieCount = cookieInfo.length
for(i = 0; i < cookieCount; i++) {
tempCookieInfo = cookieInfo[i].split("=")
if(unescape(tempCookieInfo[0]) == cookieName) {
return tempCookieInfo[1] } } }
else { return null }
}

Oh, don’t forget that big “if” block around most of the functions code. If the document.cookie object is not used by their browser, the function returns null. That way you can see if the viewer use’s cookies or not. That can be helpful because you can write code to react the lack of cookie support.

There you have it, set cookies, get cookies and a bit of use from the “split” JavaScript function.

1 Comment »

  1. Nice write up on setting cookies and overall javascript syntax. One potential problem to using javascript to set cookies though, is that if the suer doesn’t have javascript turned on then the cookie won’t be set. PHP is a good option for setting cookies too.

    Comment by nicholas — September 9, 2006 @ 9:23 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment

You must be logged in to post a comment.