The following are examples of JavaScript Cookies
Understanding Cookies
A cookie is a small text file that is stored on the end user's computer. It can be referenced any time the viewer returns to your site, provided the cookie hasn't been deleted or expired. Of course, if the viewer doesn't accept cookies, then a cookie won't be able to be set or referenced later. Keep the following points in mind when using cookies:
- Cookies must be 4K each or less
- A browser can accept up to only 20 cookies only from a single domain
- If a number of viewers don't accept cookies, this eliminates any advantages of your cookie(s) to those viewers
Netscape invented cookies to help users browse your site more effectively. For instance, if you use a script on your main page that sends one or more alerts while the page is loading, you won't want that to happen every time the viewer goes to another page on your site and then comes back to the home page. It would likely be so aggravating that you wouldn't have a visitor after it happened a few times.
The alert pops up each time the page is loaded, because HTTP lacks state persistence. Cookies fill that gap. With cookies, you can fix problems like these for any viewers that have cookies enabled.
Setting Cookies
Setting a cookie is as easy as fiving a value to the cookie property of the document object. The only restriction is that you can't have spaces, commas, or semicolons inside the string.
The only problem is that you may need to use a space, comma, or semicolon in your cookie at some point. For instance, you may want to add in some text that tells what your favorite kind of cookie is. Adding the addition information isn't difficult as long as the value does not need a space. To use a space, comma, or semicolon, you need to use the escape() method. This method translates them into somethihng a cookie accepts.
Adding an expiration date to a cookie will keep it from being deleted once the browser is closed, or it can be used to expire a cookie you no longer want to use. An expiration date is added by creating a new date object and setting the date to be used as the expiration date.
Reading Cookies
When you opened this page, you were prompted to enter your first name and email address. Below shows the results of what you entered:
Please do note, in Windows Internet Explorer, if you have cookies enabled, refreshing the page will give you a welcome window using the name you entered, a window showing the email address you entered and a window showing you the browser you are using. The same cannot be said for Netscape or Firefox. On the flip side, opening this page in Netscape or Firefox will give you the information in a string type layout for you to view. Internet Explorer does not show it at all.