JavaScript: Retrieving values from Cookies
Using JavaScript, we can display the values of cookies stored on the previous page:
- field1:
- field2:
- field3:
- field4:
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>
// Original JavaScript code by Chirp Internet: www.chirpinternet.eu
// Please acknowledge use of this code by including this header.
var getCookie = function(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>
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:
- it is deleted either by you or by the website that set it;
- it is 'rolled out' to make way for a newer cookie; or
- 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.
Related Articles - Cookies
- JavaScript Saving Form Values using Cookies
- JavaScript Using cookies to set Preferences
- JavaScript Retrieving values from Cookies
- PHP Saving a list of values in a cookie
Thanks 11 August, 2018
Thanks for the suggestion i was really worried how to get cookie value with special character Like (;semicolon) and you give me the perfect solution thanks a lot and keep it up.
Carol 14 May, 2018
The unescape() method is now deprecated (JS 1.5).
I'll suggest replacing it with decodeURI() instead.