Getting Started With Cookies |
|
Join the DiscussionRelated ResourceIf you want to store something while one page is being displayed for later on then one way to do it is to write a cookie. Cookies are small pieces of text that can actually be written to your visitor's computer and read back later. This is in fact the only way to write anything to their computer and is the only thing that you can read back in (unless you are setting up an intranet using Internet Explorer and configure the appropriate ActiveX commands). There are some limitations you need to be aware of with regard to cookies. First off there are three different types of cookies.
There are also limits on how big cookies can be and many cookies sites can set. The maximum allowed size for cookies is 4k and a site can set up to 20 cookies after which the oldest is overwritten. A bug in Internet Explorer limits the combined size of all cookies set by a site to 4k instead of allowing 4k each. The browser will also only store the last 310 cookies set so older cookies will be discarded after that number are written. First and third party cookies have an associated expiry date after which they will be deleted if they are not wiped beforehand to make space for newer cookies. Unless you have a reason for needing to keep information between browser sessions it is much better to use session cookies rather than third party cookies as they get cleaned up automatically when the browser is closed and are less likely to be disabled by your visitors. Here are a couple of functions that will read and write session cookies for you.
function readCookie(nam) {
var tC = document.cookie.split('; '); for (var i = tC.length - 1; i >= 0; i--) { var x = tC[i].split('='); if (nam == x[0]) return unescape(x[1]);} return null;} function writeCookie(nam,val) { document.cookie = nam + '=' + escape(val);} The readCookie() function takes one parameter - the name you gave to the cookie when you wrote it - and will find that particular cookie (if it still exists) from amongst all of the cookies available to the page. If it finds it then the value of the cookie will be returned from the function. Null will be returned if the cookie is not found. The writeCookie() function takes two parameters - the name of the cookie to write and the value that you want to write to that cookie. |


