A great feature of JavaScript is that it lets you set and retrieve browser cookies. In this tutorial I’ll show you how this is done, along with a simple example that remembers your name and displays it on every page.
What are cookies?
Cookies are small amounts of data stored by the web browser. They allow you to store particular information about a user and retrieve it every time they visit your pages. Each user has their own unique set of cookies.
Cookies are typically used by web servers to perform functions such as tracking your visits to websites, enabling you to log in to sites, and storing your shopping cart. However we don’t need fancy web server programming to use cookies. We can use them in JavaScript, too!
The document.cookie
property
Cookies in JavaScript are accessed using the cookie
property of the document
object. In simple terms, we create a cookie like this:
document.cookie = "name=value; expires=date; path=path;
domain=domain; secure";
…and retrieve all our previously set cookies like this:
var x = document.cookie;
Let’s look more closely at how to set and retrieve cookies.
Setting a cookie
To set a cookie, we set the document.cookie
property to a string containing the properties of the cookie that we want to create:
document.cookie = "name=value; expires=date; path=path;
domain=domain; secure";
These properties are explained in the table below:
Property | Description | Example |
---|---|---|
name =value |
This sets both the cookie’s name and its value. | username=matt |
expires=date |
This optional value sets the date that the cookie will expire on. The date should be in the format returned by the toGMTString() method of the Date object. If the expires value is not given, the cookie will be destroyed the moment the browser is closed. |
expires= |
path=path |
This optional value specifies a path within the site to which the cookie applies. Only documents in this path will be able to retrieve the cookie. Usually this is left blank, meaning that only the path that set the cookie can retrieve it. | path=/tutorials/ |
domain=domain |
This optional value specifies a domain within which the cookie applies. Only websites in this domain will be able to retrieve the cookie. Usually this is left blank, meaning that only the domain that set the cookie can retrieve it. | domain=elated.com |
secure |
This optional flag indicates that the browser should use SSL when sending the cookie to the server. This flag is rarely used. | secure |
Let’s look at a few examples of cookie setting:
document.cookie = "username=John;
expires=15/02/2003 00:00:00";
This code sets a cookie called username
, with a value of "John"
, that expires on Feb 15th, 2003 (note the European time format!).
var cookie_date = new Date ( 2003, 01, 15 );
document.cookie = "username=John;
expires=" + cookie_date.toGMTString();
This code does exactly the same thing as the previous example, but specifies the date using the Date.toGMTString()
method instead. Note that months in the Date
object start from zero, so February is 01
.
document.cookie = "logged_in=yes";
This code sets a cookie called logged_in
, with a value of "yes"
. As the expires
attribute has not been set, the cookie will expire when the browser is closed down.
var cookie_date = new Date ( ); // current date & time
cookie_date.setTime ( cookie_date.getTime() - 1 );
document.cookie = "logged_in=;
expires=" + cookie_date.toGMTString();
This code sets the logged_in
cookie to have an expiry date one second before the current time – this instantly expires the cookie. A handy way to delete cookies!
There’s no escape!
Strictly speaking, we should be escaping our cookie values — encoding non-alphanumeric characters such as spaces and semicolons. This is to ensure that our browser can interpret the values properly. Fortunately this is easy to do with JavaScript’s escape()
function. For example:
document.cookie = "username=" + escape("John Smith")
+ "; expires=15/02/2003 00:00:00";
A function to set a cookie
Setting cookies will be a lot easier if we can write a simple function to do stuff like escape the cookie values and build the document.cookie
string. Here’s one we prepared earlier!
function set_cookie ( name, value, exp_y, exp_m, exp_d, path, domain, secure )
{
var cookie_string = name + "=" + escape ( value );
if ( exp_y )
{
var expires = new Date ( exp_y, exp_m, exp_d );
cookie_string += "; expires=" + expires.toGMTString();
}
if ( path )
cookie_string += "; path=" + escape ( path );
if ( domain )
cookie_string += "; domain=" + escape ( domain );
if ( secure )
cookie_string += "; secure";
document.cookie = cookie_string;
}
This function expects the cookie data to be passed to it as arguments; it then builds the appropriate cookie string and sets the cookie.
For example, to use this function to set a cookie with no expiry date:
set_cookie ( "username", "John Smith" );
To set a cookie with an expiry date of 15 Feb 2003:
set_cookie ( "username", "John Smith", 2003, 01, 15 );
To set a secure cookie with an expiry date and a domain of elated.com
, but no path:
set_cookie ( "username", "John Smith", 2003, 01, 15, "",
"elated.com", "secure" );
Feel free to use this function in your own scripts! π
A function to delete a cookie
Another useful cookie-handling function is provided below. This function will “delete” the supplied cookie from the browser by setting the cookie’s expiry date to one second in the past.
function delete_cookie ( cookie_name )
{
var cookie_date = new Date ( ); // current date & time
cookie_date.setTime ( cookie_date.getTime() - 1 );
document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}
To use this function, just pass in the name of the cookie you would like to delete – for example:
delete_cookie ( "username" );
Again, you can use this function in your own scripts if you like. π
Retrieving cookies
To retrieve all previously set cookies for the current document, you again use the document.cookie
property:
var x = document.cookie;
This returns a string comprising a list of name/value pairs, separated by semi-colons, for all the cookies that are valid for the current document. For example:
"username=John; password=abc123"
In this example, 2 cookies have been previously set: username
, with a value of "John"
, and password
, with a value of "abc123"
.
A function to retrieve a cookie
Usually we only want to read the value of one cookie at a time, so a string containing all our cookies is not that helpful! So here’s another useful function that parses the document.cookies
string, and returns just the cookie we’re interested in:
function get_cookie ( cookie_name )
{
var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
if ( results )
return ( unescape ( results[2] ) );
else
return null;
}
The function uses a regular expression to find the cookie name and value we’re interested in, then returns the value portion of the match, passing it through the unescape()
function to convert any escaped characters back to normal. (If it doesn’t find the cookie, it returns a null value.)
Using the function is easy. For example, to retrieve the value of the username
cookie:
var x = get_cookie ( "username" );
Again, feel free to use this function with your own JavaScript code!
A simple example
In this example, we’ve created a page that prompts you for your name the first time you visit it, then stores your name in a cookie and displays your name in the page on subsequent visits.
Open the page in a new window. The first time you visit the page, it should ask you for your name and store it in a cookie. If you visit the page again at any point, it will get your name from the cookie and display it within the page.
Try closing the window that pops up, then opening it again in a new window. Notice that this time it still displays the user name that it retrieved from the cookie!
The cookie is given an expiry date of 1 year from the current date, which means that the browser will remember your name even if you close it down and re-open it.
You can clear the cookie by clicking on the Forget about me! link, which calls our delete_cookie()
function and then refreshes the page to prompt you for a name again.
You can view all the JavaScript source for the example page by switching to the other browser window now and using the View Source option in your browser. Here’s the main part of the code:
if ( ! get_cookie ( "username" ) )
{
var username = prompt ( "Please enter your name", "" );
if ( username )
{
var current_date = new Date;
var cookie_year = current_date.getFullYear ( ) + 1;
var cookie_month = current_date.getMonth ( );
var cookie_day = current_date.getDate ( );
set_cookie ( "username", username, cookie_year, cookie_month, cookie_day );
}
}
else
{
var username = get_cookie ( "username" );
document.write ( "Hi " + username + ", welcome to my website!" );
document.write ( "<br><a href=\"javascript:delete_cookie('username');
document.location.reload ( );\">
Forget about me!</a>" );
}
Notice how the function uses our get_cookie()
, set_cookie()
and delete_cookie()
library functions to do the hard work!
This tutorial has shown you how to use cookies in JavaScript to store information about your visitors. You can use the supplied functions in your own scripts to set, retrieve and delete cookies easily. Enjoy! π
Kiko says
Hi, i have autolike script, i need to add cookies to activate the script only ones for each visitor that click the like. how can i add cookies to this script. thanks
matt says
Please post your question in a new topic:
http://www.elated.com/forums/authoring-and-programming/topic/new/
cheapchop says
I see that this article was originally posted on Halloween of 2002, but have you been modifying this article as time goes by? Maybe js cookie functionality hasn’t changed much since 2002, but do you generally update your articles when syntax changes or newer functionality is offered by browsers? i like elated, thanks π
matt says
@cheapchop: Thanks for your comment! We don’t generally update articles, except in special circumstances. We prefer instead to create new articles on the topic if it’s changed a lot.
I don’t believe JS’s cookie handling has changed much since the article was written.
Angry Black Man says
https://developer.mozilla.org/en/DOM/window.escape
“escape” is not part of any officially recognized DOM standard. this tutorial should certainly be updated to use recognized DOM methods.
aside from that, this is a GREAT tutorial.
[Edited by Angry Black Man on 07-Apr-12 09:55]
chrishirst says
window.escape????
Are you reading the same article as the rest of us?
escape() is a javascript METHOD/function for encoding special characters for use in URLs or in a HTTP request.
http://www.w3schools.com/jsref/jsref_escape.asp
It is not even used in the article as in it were part of the DOM specification.
Angry Black Man says
Hi Chris,
“escape()”
is the same thing as
“window.escape()”
a lot of people are confused by this as you are. it’s understandable. there are no “free standing” functions in javascript. all functions are attached to some object in some way in the DOM. everything in javascript is located within the DOM. everything.
the reason i mentioned escape was because of cheapchop’s comments and the response he received by matt in which he declared that “I don’t believe JS’s cookie handling has changed much since the article was written”. “much” is a subjective term, but in the interests of modern browser compatibility, this is certainly a valid, useful observation that would do well to be incorporated into an article like this.
chrishirst says
“”escape()”
is the same thing as
“window.escape()” ”
No it is NOT! Maybe you don’t quite understand the fundamentals of OOP.
window.name would refer to a property or method that is a member of (or belongs to) an object class, in this case the “window” object. Just as math.floor() is a member method of the math object.
escape() is a GLOBAL method/function that does NOT rely on the Document Object Model at all, it is part of the javascript interpreter.
The list of Global properties and methods are at -> http://www.w3schools.com/jsref/jsref_obj_global.asp and a list of member properties and methods of the window object is at -> http://www.w3schools.com/jsref/obj_window.asp
If escape() was a member of any object, it should/would belong to the string object, as it operates on a string of characters.
punktobbe says
In javascript there is always a global object. In browsers this global object is the same as the window object. So actually:
However, the escape function is not part of the DOM, it is pure javascript and a property of the global object.
http://www.ecma-international.org/ecma-262/5.1/#sec-B.2.1
[Edited by punktobbe on 19-Mar-14 14:59]