DevPub
Free Mousepad

Website Statistics Now With Google Trends

Website Statistics Now With Google TrendsThe Google Trends service now offers website visitor statistics, aside from search query information. Continue Reading

How Google Works

How Google WorksA look at the myths and facts about Google, and what you should know about Google's inner workings. Continue Reading

Working With Cookies in JavaScript

Creating cookies in and then retrieving their values, all on the client side by using JavaScript. Also a look at the technology that makes cookies possible.

On Sunday, March 30th 2008 at 10:07 PM
By Louis Fernandez (View Profile)
-----   (Rated 0 with 0 votes)
First we need to define what a cookie is (aside from a delicious snack, preferably with chocolate chips!). A cookie is simply a little bit of plain text data that your browser stores. This data concerns a particular web site. Your browse stores these cookies as unencrypted text files in a location specified by the browser. Once you learn to make cookies, you can have your web page store information concerning a visitor to your site. Then when they return to your site this information can be retrieved.

Your First Cookie

Cookies are not complicated but the code is lengthy. The only way to do this is to just jump right in. So I am going to show you the code for a cookie and then walk you through it explaining it line by line:

<HTML>
<HEAD>
<TITLE>Your First Cookie </TITLE>
<SCRIPT LANGUAGE="JavaScript">
function setCookie(name, value, expires, path, domain, secure)
{
   var curCookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "")
   document.cookie = curCookie
}
function getCookie(name)
{
   var prefix = name + "="
   var cookieStartIndex = document.cookie.indexOf(prefix)
   if (cookieStartIndex == -1)
   return null
   var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
   if (cookieEndIndex == -1)
   cookieEndIndex = document.cookie.length
   return unescape(document.cookie.substring(cookieStartIndex +prefix.length, cookieEndIndex))
}
function deleteCookie(name, path, domain)
{
   if (getCookie(name))
   {
      document.cookie = name + "=" +((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") +"; expires=Thu,01-Jan-70 00:00:01 GMT"
   }
}
var expiredate = new Date()
expiredate.setTime(expiredate.getTime() + 31 * 24 * 60 * 60 * 1000)
var name = getCookie("name")
if (!name)
{
   name = prompt("Please enter your name:", "John Doe")
   setCookie("name", name, expiredate)
}
alert("Welcome back " + name)
</SCRIPT>
</HEAD>
<BODY BGCOLOR=White>
</BODY>
</HTML>

If you entered everything properly you should see a message box saying "Welcome back John Doe".

setCookie

The syntax is:

function setCookie(name, value, expires, path, domain, secure)

First note that this function takes six parameters. Your code will only supply the first three. The last three are determined by the browser. The first parameter is called name. It is simply the name of the cookie.

It’s a good idea to pick a name that is relevant to the type of data the cookie holds. The next parameter is the value or content that cookie will hold. We then have the expires parameter, which holds an expiration date for the cookie. If you do not set an expiration date, the cookie will expire the next time you reboot your PC. This is referred to as a pre-expired cookie.

Even though you don’t supply the final three parameters it’s a good idea to understand what they are. The fourth parameter simply is the path to where your browser stores cookies. The fifth parameter indicates what domain cookies are associated with. A domain can have a maximum of 20 cookies. Finally we have the secure parameter, which simply tells us if this is a secure cookie or not.

Next the code simply creates a variable to contain the cookie information and concatenates it all together. Finally we use the document object’s cookie property to add this cookie to the user’s cookie list.

var curCookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "")
// Actually placing the cookie
document.cookie = curCookie

What this function accomplishes is that it takes the values you pass it and the values that the browser itself passes it, and it creates a cookie to store that data.

getCookie

The next function we examine is the code for the getCookie function. This is called to see if a valid cookie exists for this web page visitor. If it does, the function will simply return a null value. At that point you can prompt the user to enter the data, and then call setCookie(). However, if it does find a match, you can then use that data.

The function begins with this line of code:

var prefix = name + "="var cookieStartIndex = document.cookie.indexOf(prefix)

This code segment is creating a variable named prefix. That variable is set to equal the starting point, in the cookie file, of the cookie name that was passed to this function. This function will use the document object’s cookie project to see if it can find this cookie. If it can, then it will return the index, and the cookie’s value can be read in. If not, it will return a null. In fact, the very next line takes care of this:

if (cookieStartIndex == -1)
return null

If cookieStartIndex cannot be found, simply have the function return a null, indicating that no cookie was found.

The next few lines try to find the ending point of this cookie. If one cannot be found, it is assumed that this is the last cookie your browser has in its cookie list and the end of this list is assumed to be the end of this cookie:

var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex+ prefix.length)

if (cookieEndIndex == -1)
cookieEndIndex = document.cookie.length

Now once the function has determined that the cookie exists and that it has a start point as well as an ending point, then it’s time to simply return the contents of that cookie. This is what the final line of the function accomplishes:

return unescape(document.cookie.substring(cookieStartIndex +prefix.length, cookieEndIndex))

The third function, deleteCookie(), simply deletes a cookie if you pass it the cookie name. In the previous example this function was not actually called, but I thought I should show it to you in case you need it later.

Calling the Functions

Now how do we actually use these functions to get cookies and to create them? Well, the last few lines of the script accomplish this, so let’s give them a look. First, we have two lines of code that create a Date object and increment its value:

var expiredate = new Date()
expiredate.setTime(now.getTime() + 31 * 24 * 60 * 60 * 1000)

This expiredate object will be used to set the expiration date of our cookie. You can use the date functions to set this expiration date to any date you wish. I just picked this particular date for illustration purposes.

Now that we have an expiration date (and that will only be used when we set a new cookie, not when we get a cookie) we will now see if the cookie we want already exists on the web page visitor’s machine.

var name = getCookie("name")

This code is really quite simple, but effective. We simply call the getCookie function and find out what it returns for the name cookie. If it finds a valid name, then we can simply use that name. If not, then we will get a null for a return value, in which case we can simply prompt the user to enter their name then use the setCookie function to create a cookie holding their name:

if (!name)
{
name = prompt("Please enter your name:", "John Doe")
setCookie("name", name, expiredate)
}
alert("Welcome back " + name)

And that, in a nutshell, is how our cookie script works. It is really not that complicated, it is simply long. So in order to make sure you do understand the concepts, let’s examine another script that stores a somewhat different cookie.

Creating Another Cookie

This cookie works similar to the previous one, and I hope that by examining both cookies you will get a good understanding of how cookies work. This script asks the user what background color they would prefer when viewing the web page, and saves that value in a cookie. Then anytime they visit the web page, it uses the background color they selected.

<HTML>
<HEAD>
<TITLE>Your Second Cookie </TITLE>
<HEAD>
<SCRIPT LANGUAGE = "JavaScript">
var expiredate= new Date();
expiredate.setTime(expiredate.getTime() + (30*24*60*60*1000))
var backcolor = getCookie("bgcolor")
if (backcolor == null)
{
   backcolor = prompt("What is your favorite background color?")
   setCookie("bgcolor", backcolor, expiredate)
}
document.bgColor=backcolor
function setCookie(name, value, expires, path, domain, secure)
{
   var curCookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "")
   document.cookie = curCookie
}
function getCookie(cookiename)
{
   var prefix = cookiename + "="
   var cookieStartIndex = document.cookie.indexOf(prefix)
   if (cookieStartIndex == -1)
      return null
   var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex+prefix.length)
   if (cookieEndIndex == -1)
      cookieEndIndex = document.cookie.length
   return unescape(document.cookie.substring(cookieStartIndex+prefix.length, cookieEndIndex))
}
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>

If you entered the code properly, you should be able to see a prompt in the browser window.

Hopefully you notice several similarities between this script and the last one. But let us go over this one together, just to make sure you understand everything that is happening. The first difference is merely structural. In this script I placed the call to the functions first, then the function definitions. This is the opposite of the order used in the previous script. I did this on purpose to show
you that the order in which you do these actions really makes no difference.

Let’s take a look at the first few lines of code and see what they are doing:

var expiredate= new Date();
expiredate.setTime(expiredate.getTime() + (30*24*60*60*1000))
var backcolor = getCookie("bgcolor")

First, we create a date object called expiredate. As you might guess, this is going to hold the expiration date for the cookie. We then set the expiration date for some time beyond the current time. Next, we call the getCookie function to retrieve the contents of the cookie named bgcolor. Whatever is returned is placed in the variable backcolor. If the cookie is found, then backcolor should contain some color. If no matching cookie is found, then we will get a null value in the variable backcolor.

Next we check to see if the value of backcolor is null. If so, we are going to prompt the user to enter their preferred color and then create a cookie to save that information. We will then set the background color of the current web page to the color the user has selected:

if (backcolor == null)
{
backcolor = prompt("What is your favorite background color?")
setCookie("bgcolor", backcolor, expiredate)
}
document.bgColor=backcolor

We do not need to closely examine the setCookie and getCookie functions because they are exactly identical to the ones used in the previous function. This illustrates a very important point. The process of creating a cookie, or retrieving one, is the same regardless of what you choose to name a cookie or what value you place in the cookie. This means you can use these same cookie scripts, with some minor alterations, to create cookies to save any data you might wish to save.

Behind Cookies

The way a client’s browser communicates with the web server is via HTTP (Hypertext Transfer Protocol). When a user requests a specific page, the browser sends that request to the web server. This activity is all transparent to the web page user. Among the items requested, an HTTP request includes a header that defines the most important attributes, such as the URL of the requested page. An HTTP request also includes the cookies.

The server then returns an HTTP response. This response also has a header that contains valuable information. The general structure of an HTTP header is as follows:

Field-name: Information

When the server returns an HTTP object to the client, it may also transmit some state information for the client to store as cookies. Since a cookie is basically simple text, the server-side script does not have the ability to abuse the client machine in any way. In addition to its textual value, a cookie contains several attributes, such as the range of URLs for which the cookie is valid. Any future HTTP requests from the client to one of the URLs in the above range will transmit back to the server the current cookie’s value on the client.

An HTTP cookie is introduced to the client in an HTTP request using the following syntax:

Set-Cookie: NAME=VALUE; expires=DATE; path=pathName; domain=DOMAIN_NAME; secure

The attributes are as follows:

name=value

This simply specifies the name of the cookie and the value to be stored in the cookie. Technically, this is the only field that is required. All others are purely optional.

expires=date

As you probably guessed, this attribute simply sets an expiration date for the cookie. This field is optional. However, if no expiration date is set, a cookie will expire the next time the client machine is rebooted. The date string is formatted as follows:

Wdy, DD-Mon-YYYY HH:MM:SS
domain

The domain attribute makes sure that only hosts within the specified domain can set a cookie for the domain. Domains must have at least two or three periods, to avoid collision between domains of the form .com, .edu, etc. There are seven common top-level domains that require at least two periods in their domain name: com, edu, net, org, gov, mil, and int. All other domains require at least three periods in their domainName. An example of a domain name would be www.wordware.com.

The default value of domain is the host name of the server which generated the cookie response.

path=pathName

Path specifies a subset of URLs in a domain for which a cookie is valid. Basically once you have found an appropriate domain, you have to find the individual web site within that domain that is relevant to this cookie.

secure

If a cookie is marked secure, it will only be transmitted across a secured communication channel between the client and the host.


Rate Rate this tutorial

Comment Comment on this tutorial
Name: Email:
Message:

Comment Current Comments