skip to content

JavaScript: Retrieving values from Cookies

 Tweet0 Shares0 Tweets

Using JavaScript, we can display the values of cookies stored on the previous page:

These values will be stored in your browser for a period of 30 days. Cookie values are only accessible from the same domain as the page from which they were set. In other words these cookie values can be accessed anywhere on The Art of Web, but not from any other website.

The getCookie() function

<script type="text/javascript"> // Original JavaScript code by Chirp Internet: www.chirp.com.au // Please acknowledge use of this code by including this header. function getCookie(name) { var re = new RegExp(name + "=([^;]+)"); var value = re.exec(document.cookie); return (value != null) ? unescape(value[1]) : null; } </script>

To display the value of a cookie called field1 we simply use the following:

<script type="text/javascript"> document.write(getCookie("field1")); </script>

If you view the source of this page you will see that this is how the cookie values are being presented in the list above.

document.cookie

Cookies are stored in the document.cookie JavaScript object which in your browser currently holds the following name/value pairs:

Each name/value pair displayed above represents a single cookie. A single cookie can hold up to 4kb of text, and for each domain name your browser will normally permit up to 20 cookies.

Stale cookies

A cookie will reside in your browser until:

  1. it is deleted either by you or by the website that set it;
  2. it is 'rolled out' to make way for a newer cookie; or
  3. it reaches it's expiry date.

As mentioned above, your browser sets a limit both on the size and the number of cookies it allows for a single domain. If the limit on the number of cookies has already been reached and a new one is set, the oldest cookie will be expired to make way for the new one (FIFO).

One common oversight is in setting a cookie with an expiry date (1 year for example) and then never re-setting the cookie. After one year, regardless of other actions, the cookie will expire. If you have a website that relies on cookies to save user preferences or identify repeat customers you should make sure to re-set the cookie every time they visit.

< JavaScript

Send a message to The Art of Web:


used only for us to reply, and to display your gravatar.

<- copy the digits from the image into this box

press <Esc> or click outside this box to close

Post your comment or question
top