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.
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:
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:
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
This is superior to writing a huge number that you'll forget the meaning of in the future.
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, "/".
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.
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.
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.
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:
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.
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.
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.
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.
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:
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:
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.
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:
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.
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:
For example, to delete the cookie set in the example above, do this:
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).
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.
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 the ability of search engines to run complicated JavaScript code to produce the same output as a web browser is not guaranteed.
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-2018 by Christopher Heng. All rights reserved.
Get more free tips and articles like this,
on web design, promotion, revenue and scripting, from https://www.thesitewizard.com/.
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 https://www.thesitewizard.com/thesitewizard.xml. You can read more about how to subscribe to RSS site feeds from my RSS FAQ.
This article is copyrighted. Please do not reproduce or distribute this article in whole or part, in any form.
It will appear on your page as:
How to Use Cookies in JavaScript