JavaScript cookies Free Web Design Tutorials
Home   HTML CSS JavaScript PHP MySQL Usability Glossary
JavaScriptBasicsRunning a ScriptVariablesExpressions and OperatorsObjects.Properties.MethodsThe Date ObjectStringsRegular ExpressionsDefining RegExp PatternsBranches and ConditionsLoopsArraysArray MethodsSorting ArraysUser-Defined FunctionsJavaScript CookiesCookiesWindowsFrames

Home > JavaScript > Cookiesprinter version

JavaScript Cookies

A JavaScript cookie is a small file (no greater than 4Kb) that holds data and is stored by the web browser on the user's machine.

Cookies can be created, read from, modified or deleted and provide a means of saving state, allowing data to be shared across web pages.

A cookie is a property of the Document object and accepts the following attributes.

  1. Name - the name of the cookie.
  2. Value - the data to be stored in the cookie.
  3. Expiry Date - how long the cookie is to persist.
  4. Path - a path that determines which web pages will have access to the cookie.
  5. Domain - the domain that the cookie is associated with.
  6. Secure - determines if cookie data is transmitted over an http or https connection.


Creating a Cookie

The syntax of cookie creation is shown below with all attributes displayed except secure, which isn't widely used.


Basic Example of Storing a Cookie
<script language="javascript" type="text/javascript">
    document.cookie = "mycookie=Hello; expires=31/7/2009 14:45:00; path=/; domain=mydomain.com;";
</script>


The code above creates a cookie that expires at 2.45pm on 31/7/2009 and stores the string "Hello". The cookie attributes are explained below.

The name attribute

In this case the name of the cookie is mycookie and is followed by = then the string to store. However cookies don't allow commas, semicolons or whitespace within the string.

Since you're quite likely to use these characters in a cookie then you should use the JavaScript escape() function when creating the cookie and the unescape() function when you read the cookie.

The expires attribute

This sets the expiry time and date of the cookie. If omitted then the cookie expires at the end of the browser session (i.e. when the browser is closed).

The path attribute

This determines the path to web pages that are allowed access to the cookie. For example if only web pages within the products directory should have access to the cookie then the path would be /products.

In the example above the path / means the cookie may be accessed by any web page or directory within the document root.

If omitted then the cookie can only be accessed by web pages in the same directory as the web page that created it or by pages within any subdirectories.

The domain attribute

Setting this allows the cookie to be accessed by any web page on the domain, even if it's held on a different server, as well as any subdomains.

If omitted then the cookie may only be accessed by web pages on the server from which the cookie was created.

Using the escape() Function

If the cookie value includes commas, semicolons or whitespace then use the escape() function and concatenation to construct the string.

The example below sets an expiry time and date and can be accessed by any web page in same directory as the script creating the cookie.

Example of Storing a Cookie Using escape()
<script language="javascript" type="text/javascript">
    document.cookie = "mycookie=" + escape("Hello World") + ";expires=31/7/2008 14:45:00";
</script>


Reading a Cookie

To read the contents of a cookie you read the cookie property. This returns a name value pair in the form name = value where name is the name of the cookie and the value is the cookie string.

If there is more than one cookie then the string is a list of name value pairs separated by semicolons.

The value returned does not include any of the attributes set when the cookie was created, such as expiry etc.

If you used the escape() function to write the cookie then use the unescape() function to read it.

Example of Reading a Cookie Using unescape()
<script language="javascript" type="text/javascript">
    document.cookie = "mycookie=" + escape("Hello World");
    x = unescape(document.cookie);

    // This prints out mycookie=Hello World
    document.write(x);
</script>


Normally when you create a cookie it's to contain multiple pieces of information separated by a delimiter such as a colon.

If this is the case then use JavaScript string methods to chop up the string into it's different fields.

Deleting a Cookie

To delete a cookie simply set the expiry date to a date in the past.

Example of Deleting a Cookie
<script language="javascript" type="text/javascript">
    document.cookie = "mycookie=" + escape("Hello World");

    // This will delete mycookie
    document.cookie = "mycookie=";expires=Wed, 02-Aug-2000 00:00:00 GMT";
</script>


Previous - JavaScript User-Defined Functions Previous - User-Defined Functions     Next - Windows Next - JavaScript Windows


Privacy | Terms | Contact | Links | Sitemap | RSS Feeds RSS and JavaScript Feeds
©2009 www.webdesignworkmate.co.uk all rights reserved 
Design and Production by smallbizonline website design © 2000-2009
Valid HTML 4.01! Level Double-A conformance icon, W3C-WAI Web Content Accessibility Guidelines 1.0Valid CSS!
Recommended Reading
Javascript the definitive guide

Javascript and DHTML cookbook

Pro javascript techniques

simply javascript