Saturday, April 30, 2011

JavaScript Cookies - XVII


Cookies are small text files that sit on your hard disk. Cookies are created when you visit websites that use cookies to store information that they need (or prefer). Websites often use cookies to personalise the user experience - such as remembering your name (assuming you supplied it previously) or remembering the items in your shopping cart from previous visits.
Despite the many misconceptions about cookies being malicious, they are quite harmless. Cookies can't give your personal details to other websites, or transmit a virus or anything like that. A cookie can only be read by the server that created it. Websites normally use cookies to make its users' lives easier, not harder.

Creating Cookies in JavaScript

document.cookie =
"myContents=Quackit JavaScript cookie experiment;
 expires=Fri, 19 Oct 2007 12:00:00 UTC; path=/";
Now check your cookies folder to see if the cookie was created. Alternatively, write code to read the cookie.
Note: If the cookie wasn't created, check the expiry date - it needs to be a date in the future.
You can update this value by using the same code with a different value. If you want to add a second value, simply use a different variable name (for example "myContents2=").

Reading Cookies in JavaScript

document.write(document.cookie);
You simply reference the cookie using document.cookie. The only problem with the above code is that it outputs the equals sign and everything before it (i.e. "myContents="). To stop this from happening, try the following code:
document.write(document.cookie.split("=")[1])

Deleting Cookies in JavaScript

To delete a cookie, you can use the same code you used to create it but this time, set the expiry date in the past:
document.cookie =
"myContents=Quackit JavaScript cookie experiment;
 expires=Fri, 14 Oct 2005 12:00:00 UTC; path=/";
Once you are comfortable with JavaScript and cookies, you can do things like use the getDate() function to set the date at a date in the future (say, 6 months), creating a function for setting and naming your cookies etc.

No comments:

Post a Comment