JavaScript Cookies
In JavaScript, we set and remove cookies with the document.cookie object. What is a cookie?
[Wikipedia] HTTP cookies, sometimes known as web cookies or just cookies, are parcels of text sent by a server to a web browser and then sent back unchanged by the browser each time it accesses that server. HTTP cookies are used for authenticating, tracking, and maintaining specific information about users, such as site preferences and the contents of their electronic shopping carts. The term “cookie” is derived from “magic cookie,” a well-known concept in unix computing which inspired both the idea and the name of HTTP cookies.
In the example that follows, we’ll look at using cookies in the context of an HTML form. When the user fills it out and opts to have the web page “remember” him the next time he visits, a cookie will be set containing his username.
To set a cookie, we simply insert a name-value pair into the document.cookie object. Example:
document.cookie = ‘username=johnbrown’
Spaces, semi-colons, equal signs are not permitted. In fact, the value part must be specially encoded with the escape() function. Spaces will turn into the familiar %20 and so on. To decode it, we use the unescape() function.
There is a special name that we can include in our cookie called expires which is a date in GMT format.
document.cookie = ‘username=johnbrown;expires=Wed, 31 Oct 2007 18:32:47 GMT’
This instructs the cookie that we would like it to expire on the date above. Please do not try to create a cookie that will last indefinitely. Users have the freedom to delete cookies at will. They often do and the browsers often remove cookies that haven’t been touched for a while.
Here’s how we read the current date and time into a variable
var myDate = new Date()
Here’s the current date and time in GMT format
alert(myDate.toGMTString())
Have no fear. By assigning a value to document.cookie we are not overwriting its contents. Only the name-value pair you are trying to add will be overwritten.
So, this will produce the cookie “username=joebloke;gender=male” without the double quotes of course:
document.cookie = ‘username=joebloke’
document.cookie = ‘gender=male’
Let us say that we no longer need the gender information, how do we delete a name-value pair from the cookie?
We’ll have to assign a null value to the name.
document.cookie = ‘gender=’
That takes care of that.
Now, what if we no longer need our cookie, how do we get rid of it. We’d have to set an expiry date some time in the past.
Take a look at the example that follows:
To download the .ZIP compressed example, click here
Posted in JavaScript on October 31st, 2007 by me | |
Leave a reply
You must be logged in to post a comment.
