Thursday, April 10, 2008

How to Use Cookies in JavaScript

Cookies are bits of data that a browser stores in your visitor's computer. They are useful in that they allow you to store things like your visitor's preferences when they visit your site, or other types of data specific to a particular user. This tutorial deals with how you can use JavaScript to create, store, retrieve and delete cookies.
What Kinds of Data Can Be Stored in a Cookie?
A cookie is basically a string of text characters not longer than 4 KB. Cookies are set in name=value pairs, separated by semi-colons. For example, a cookie might be a string like the following:
"theme=blue; max-age=60; path=/; domain=thesitewizard.com"
This example cookie has 4 variable/value pairs:
max-age, which is set to 60,
path, which is set to the slash character "/",
domain, which is set to "thesitewizard.com",
and theme, which is set to "blue".
The variables "max-age", "path" and "domain" are special variable names that are recognized by the browser to control things like the lifespan of the cookie and the URLs for which the cookie is valid. Only the "theme" variable in my example contains the real data that I wish to set. You can create any variable name you want, and set it to whatever value you wish, subject to the following constraints:
max-age
Cookies have, by default, a lifespan of the current browser session. As soon as your visitor closes his browser, your cookie disappears. To make it last longer, you will need to set the max-age variable to contain the number of seconds (yes, seconds) you want the cookie to last.
For example, if you want your cookie to last 30 days, set it to 2,592,000. Actually instead of pre-calculating this and putting it into your script, you can have the JavaScript interpreter calculate it for you at run time, and simply encode it as
"theme=blue; max-age=" + 60*60*24*30 + "; path=/; domain=thesitewizard.com"
This is superior to writing a huge number that you'll forget the meaning of in the future.
path
By default cookies are valid only for web pages in the directory of the current web page that stored them, as well as its descendants. That is, if a cookie is set by http://example.com/abc/webpage.html, it will be valid for http://example.com/abc/yet-another-page.html as well as http://example.com/abc/Sub-Folder/index.html, but not for http://example.com/index.html.
If you want the cookie to be valid in some other directory, say, http://example.com/special/, you will need to set the path variable to contain the value "/special". If you want the cookie to be valid everywhere on your site, set it to the root of your web directory, that is, "/".
domain
Another special variable name that you may want to take note of is the domain variable. Cookies set in sub-domains like www.example.com will only be valid for that subdomain. If you want it to be valid for all sub-domains of example.com, you will need to set the domain to point to "example.com". The cookie will then be valid for "www.example.com", "blog.example.com", and whatever other subdomains that you may have.
Note that for security reasons, if your domain is example.com, browsers will not accept a cookie for a different domain, like google.com.
secure
There's another variable that has special meaning: secure. This variable should not be assigned any value. Including it means that the cookie will only be sent if your visitor is visiting your website over a secure connection.
expires
The expires variable is obsolete although still supported by today's browsers. Use the max-age variable instead, since it is easier to use. Be careful not to use "expires" as a variable name to store your data as well.
No spaces, commas, semi-colons
Your cookie values cannot have any embedded whitespaces, commas or semi-colons. If you have any, they must be converted to its "encoded" equivalent. The easiest way to do this is to use the encodeURIComponent() function to encode it, and the decodeURIComponent() function to decode it when you read the cookie.
Expanding on my earlier example, if you want to set a "theme" variable to "blue theme", you can do it this way:
"theme=" + encodeURIComponent("blue theme") + "; max-age=" + 60*60*24*30 + "; path=/; domain=thesitewizard.com"
Of course in the above case, since there is only one space character to encode, you can do it manually as "blue%20theme" as well.
Cookie Limits
Although different browsers may implement different limits for cookies, the bare minimum that they are supposed to support is as follows:
Cookie length: 4 KB. The total length of your string, including all the variables with special meaning, should not be more than 4,096 characters.
Maximum number of cookies per web server: 20.
Total number of cookies supported by the browser: 300. This includes cookies stored by other websites.
How to Set a Cookie
Setting a cookie is extremely simple. Just assign the string you want for the cookie to the document.cookie property. For example, if I want to set the cookie given in my example above, I can simply include the following JavaScript code.
document.cookie =
"theme=" + encodeURIComponent("blue theme") +
"; max-age=" + 60*60*24*30 +
"; path=/; domain=thesitewizard.com" ;
To make your life easier, you may want to include the following function in the HEAD section of your web page, and then use it to set your cookies.
(Note: If you are using IE 6, you may have difficulty cutting/copying the code. See my other article for the solution.)
function set_cookie ( cookie_name, cookie_value,
lifespan_in_days, valid_domain )
{
// http://www.thesitewizard.com/javascripts/cookies.shtml
var domain_string = valid_domain ?
("; domain=" + valid_domain) : '' ;
document.cookie = cookie_name +
"=" + encodeURIComponent( cookie_value ) +
"; max-age=" + 60 * 60 *
24 * lifespan_in_days +
"; path=/" + domain_string ;
}
To set a cookie with the name "colourscheme" and the value "Shades of Purple" that will last 7 days for all URLs in the domain example.com, call the function this way:
set_cookie( "colourscheme", "Shades of Purple", 7, "example.com" );
The function saves you from the tedium of remembering all the details needed to set a cookie. It uses the defaults that most webmasters want, like making the cookie valid for all paths in the domain, and setting the cookie in terms of days (instead of seconds). In addition, if you only want to set the cookie for your current domain, you can call it without the third parameter:
set_cookie( "colourscheme", "Shades of Purple", 7 );
How to Read a Cookie
Setting a cookie is great and all that, but a cookie is only useful if one can actually read what one has set previously.
To read a cookie, just read the string currently held in document.cookie. Since the string includes all the usual overhead for a cookie, like "max-age", "path" and "domain", you will need to parse the string to obtain the value you want. There are many ways to do this, such as splitting the string into separate tokens, using one of the substring search functions, or using regular expressions.
The following function allow you to easily get the cookie value you want by simply specifying the variable name.
function get_cookie ( cookie_name )
{
// http://www.thesitewizard.com/javascripts/cookies.shtml
var cookie_string = document.cookie ;
if (cookie_string.length != 0) {
var cookie_value = cookie_string.match (
'(^;)[\s]*' +
cookie_name +
'=([^;]*)' );
return decodeURIComponent ( cookie_value[2] ) ;
}
return '' ;
}
To use the function, include it somewhere in the HEAD of your web page, and call it with the name of the cookie variable that you set earlier. The string returned will be the decoded string you used to set the cookie with set_cookie(). The function does the hard work of searching for the string, separating the value out, and decoding it.
For example, to retrieve the "colourscheme" cookie set earlier, do the following:
colourscheme = get_cookie( "colourscheme" );
If get_cookie() cannot find the cookie, it will return an empty string. This may happen even if you have set a cookie, since the visitor may have deleted it, or alternatively, disabled cookie support in his/her browser.
How to Delete a Cookie
There are times when you may want to delete a cookie, such as when a visitor logs out of your site. To do this, set the max-age variable to 0 (zero) for the same cookie in the same path and domain. You can use the following function to do this:
function delete_cookie ( cookie_name, valid_domain )
{
// http://www.thesitewizard.com/javascripts/cookies.shtml
var domain_string = valid_domain ?
("; domain=" + valid_domain) : '' ;
document.cookie = cookie_name +
"=; max-age=0; path=/" + domain_string ;
}
For example, to delete the cookie set in the example above, do this:
delete_cookie( "colourscheme", "example.com" );
Note that this function assumes that you have set the cookie using my set_cookie() function, which always sets the path as "/". If you used your own cookie setting code that does not set the path to the root of your website, you should write your own cookie deletion code that specifies the same path you set.
Furthermore, if you did not set a domain name when calling set_cookie(), you should also not use a domain name when deleting the cookie. In such a case, you can do it like this, omitting the second argument (parameter).
delete_cookie( "colourscheme" );
Cautionary Notes
The Provided Functions Work in Tandem
The functions I provided above are designed to work together.
For example, as noted above, don't use my delete_cookie() function on cookies you set yourself with your own or some other person's code. It may not work if the path is not set the way I did in my set_cookie() function. There may be other inter-dependencies as well.
Take the Usual JavaScript Precautions
Since the code is in JavaScript, if your visitors disable JavaScript execution in their browser, your cookie code will fail. You should try to design your website so that it will still be functional and readable even if JavaScript is not available. Your site need not have all the functionality that it has when JavaScript is available, but it should still work. This is also needed for if you want your website to rank well in the search engines, since search engines operate like browsers with no JavaScript capability.