How to Use Cookies in JavaScript

How to set, retrieve and delete cookies on your website


How to Use Cookies in JavaScript

by Christopher Heng, thesitewizard.com

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:

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:

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

Conclusion

Armed with the above code and functions, you should be able to write JavaScripts that make use of cookies on your page without having to reinvent the wheel.

Copyright © 2008-2014 by Christopher Heng. All rights reserved.
Get more free tips and articles like this, on web design, promotion, revenue and scripting, from http://www.thesitewizard.com/.

thesitewizard™ News Feed (RSS Site Feed)  Subscribe to thesitewizard.com newsfeed

Do you find this article useful? You can learn of new articles and scripts that are published on thesitewizard.com by subscribing to the RSS feed. Simply point your RSS feed reader or a browser that supports RSS feeds at http://www.thesitewizard.com/thesitewizard.xml. You can read more about how to subscribe to RSS site feeds from my RSS FAQ.

Please Do Not Reprint This Article

This article is copyrighted. Please do not reproduce this article in whole or part, in any form, without obtaining my written permission.

Related Pages

New Articles

Popular Articles

How to Link to This Page

It will appear on your page as:

How to Use Cookies in JavaScript





Home
Donate
Contact Us
Link to Us
Topics
Site Map

Getting Started
Web Design
Search Engines
Revenue Making
Domains
Web Hosting
Blogging
JavaScripts
PHP
Perl / CGI
HTML
CSS
.htaccess / Apache
Newsletters
General
Seasonal
Reviews
FAQs
Wizards

 

 
Free webmasters and programmers resources, scripts and tutorials
 
HowtoHaven.com: Free How-To Guides
 
Site Design Tips at thesitewizard.com
Find this site useful?
Please link to us.