Cookie
The Cookie object is a custom object designed to ease the work with cookies. This little tutorial will demonstrate how to use the object.
General usage
Before we attempt to use cookies in our application we want to know whether the client has enabled cookies. This is done with the function Cookie.isEnabled. Assuming the function load is called on the onload event of the body tag one usage is
1 function load(e) { 2 // Return true if cookies are enabled; false otherwise 3 var enabled = Cookie.isEnabled(); 4 // If cookies are not enabled 5 if (!enabled) 6 alert('You must enable cookies.'); 7 }
Once we know that cookies are enabled we can create a cookie like this.
1 // A variable which we want to save 2 var info = 'Some info we want to save in a cookie'; 3 // Create the cookie 4 var c = new Cookie('myCookie',604800); 5 // Save the variable in the cookie 6 c.info = info; 7 // Store the cookie on the client 8 c.write();
In the above example we have created a cookie with the name 'myCookie' which will be saved on the client for 604800 seconds which is exactly one week. The cookie stores the variable info which we can then retreive at a later time like this
1 // Get cookie with the name 'myCookie'. 2 var c = Cookie.read('myCookie'); 3 // Output is 'Some info we want to save in a cookie' 4 alert(c.info);
If you want to remove a cookie entirely from the client you can use
1 // Get cookie with the name 'myCookie'. 2 var c = Cookie.read('myCookie'); 3 c.remove();
Note that the cookie is most likely not deleted until the user closes the browser.
The Cookie object also provide a custom toString method which you can use for debugging. It will output whatever is stored in the cookie as well as the attributes of the cookie (max-age, path, domain and secure). To use simply use the cookie object in a string context like
1 // Get cookie with the name 'myCookie'. 2 var c = Cookie.read('myCookie'); 3 // Implicitly call the toString 4 alert(c);
Customizing the Cookie object
The Cookie object has two constants and two functions which you can customize to your need
- Constant Cookie.valueSeparator
The token used when separating name and value of a variable. The default value is a : (a colon) but if this interferes with your preferences you can change it to any printable character. - Constant Cookie.pairSeparator
The token used when separating name/value pairs. The default value is a & (an ampersand) but you can change it to any printable character. - Function Cookie.encode
The function used for encoding variabled before saving the cookie. Default is theencodeURIComponentfunction. - Function Cookie.decode
The function used for decoding variabled after reading the cookie. Default is thedecodeURIComponentfunction.
