Looking for the previous guiStuff?
It's still here, the content didn't go anywhere. You may want to check out this new guiStuff though -- It's rather informative.
References/Tutorials:
Intro Documents:
guiStuff:
::Stuff for the multi-spec coder;
Coding, formats, standards, and other practical things.
Home // JavaScript // Cookies
<!-- JavaScript
Cookies in JavaScript
As we all know that HTTP is a stateless protocol, which means that once you have requested something to the server and the server has fulfilled the request by giving you the required document it does not remember who you after the completion of the request. Now that's where the use of cookies comes into play. Cookies are just variables that are stored in a text file or a file without any extension. It contains information such as 'name of the cookie', 'expiry', etc. They are always stored on the client side, and are referred to when called upon by the server.
Take for example emails; we check our mails all day sometimes after every hour or two. When we enter the username and password for any web mail, some information is stored in the cookies. After sometime when we again click on refresh to check if we have got any new mails it will remember our details and show us our inbox instead of a login page. Now this would not have been possible if it weren't for cookies. The server will request for our login information from the cookie and if it proves to be valid we need not enter the username/password again. Cookies are also used to store user preferences, such as color other design appearance details of a website, etc.
Let's now examine the entire cookie structure. First we shall see how the cookie actually looks like and then the following part will explain you each part of the cookie.
document.cookie = "name_of_cookie=value_of_cookie;
expires = Fri, 4 Aug 2006 11:00:22 UTC; path=/"
The three main constituents of a cookie are: name and value of the cookie, expiry and domain/path of the server which the cookie has to communicate with. The name and value is self explanatory, and the expiry is the date till which the cookie should be valid till. If there is no expiry set for the cookie, then immediately after you close the browser window the cookie will be deleted. The domain/path is a key factor here. The domain which is set in the cookie has to be the domain which is storing the cookie, and is normally default. Now if you download a cookie from google.com the cookie value will have to contain the information that the cookie is supposed to communicate with google only and not with Microsoft.com. This is an extremely serious issue and is needed for security purposes. The path refers to the sub-directory which should be the lowest accessible one in the current domain.
/ means that the cookie is valid throughout the domain with all sub-directories. If a domain stores the path as; /news in the cookie then only the url having www.domain.com/news/... can communicate with the cookie. /reviews will not have the authority to read or write cookie values for /news.Cookies are accessed and created by using the
document.cookie statement. You can access cookies just the same way you work with Strings. As you can see from the above cookie example the values are separated using a semicolon. We can simply use the String.split( ) function which we use to split strings, to separate the cookie name, expiry and path.
There are three things you need to learn for knowing how to handle cookies:Creating cookies
Have a look at the function below to see how we can create a cookie. We will make a function 'cookie_create' accepting 3 parameters: name of the cookie, value stored in the cookie and days to expire.
function cookie_create(c_name,c_value,exp_days)
{
var c_date = new Date( );
c_date.setTime(c_date.getTime()+(exp_days*86400000));
var expire = "expires="+c_date.toGMTString();
document.cookie = c_name+ "=" +c_value "; "+expire+"; path=/";
}
The function converts the days to expire to a date using the Date manipulation functions. The
setTime( ) sets the date accordingly and the toGMTString( ) function converts it to UTC time. Have a look at a detailed explanation of these functions if need in the Date tutorial. The last line just concatenates the all the variables to one string and stores it in document.cookie.Reading cookies
The function below compares the cookie to be searched for with the cookies previously stored by the browser.
function cookie_read(c_name)
{
var comp = c_name + "=";
var cooks = document.cookie.split(';');
for(var i=0;i < cooks.length;i++)
{
var check = cooks[i];
while (check.charAt(0) == " ")
check = check.substring(1,check.length);
if (check.indexOf(comp) == 0)
return check.substring(comp.length,check.length);
}
return null;
}
The first statement creates a variable
comp which will be the name of the cookie and = concatenated, so we can use this string to compare the cookie name amongst all the cookies. We split all the cookies which are stored by the browser and split them by ; and store it in an array cooks. We then find a substring; using the while loop we keep moving ahead till we reach a character except " "(space). When this is reached we would have encountered the first letter of the name of the cookie. We shall continue to do this until we find check with a substring comp in it.This will scan all the cookies and if no match occurs a
null is returned.Deleting cookies
To delete a cookie is very simple. We just create a new cookie as we did earlier with the same name but here we set the expiry to any date before today's date. The browser will now detect that it has expired and the cookie will be deleted.
function cookie_delete(c_name)
{
cookie_create(c_name,"",-1);
}
This will set the cookie to expire to yesterday's date.
Implementation
We can now see how to put all these functions together in a small script. Suppose you want to greet your visitors with a welcome message. What we can do here is, if it's a new user visiting your site then you can display a prompt asking him for his name or if it's a return visit by the same person it will check the cookie for the user's name and display a message to welcome the user back to your site.
function check_user( ) {
name = cookie_read('name')
if (name!=null)
alert("Welcome back" +name)
else {
name=prompt("Enter your name")
if (name!=null && name!="") {
cookie_create("name",name,7)
}
}
}
The above code will use both the functions we discussed earlier. You can now call the function
check_user( ) when the document loads within the <BODY onload = "check_user()"> tag.Return to the JavaScript section, or go the to Main page.