JavaScript Page 2 - Using Cookies With JavaScript |
Before you start using cookies, there are a few things you should be aware of:
Now, with the caveats out of the way, let's take a look at the ingredients that make up a cookie. 1. The first element in a cookie is a "name" attribute. Here, the "name" is a string used to identify the cookie (akin to a variable name), followed by the data to be stored in the cookie. This variable-value pair is required; you can't bake a cookie without it. For example, 2. A cookie can also contain an "expires" attribute, which specifies how long the cookie is valid for. For example,
Setting this element to a date in the past will usually cause the browser to delete the cookie. 3. You can also add a "path" attribute to a cookie -- this states where the cookie may be accessed from on the Web site. Most often, this is set to the server's document root
to ensure that the data in the cookie is available to all the scripts on the site. 4. The "domain" attribute allows you to set a domain name for the cookie. Again, this is optional, and might look like this:
5. Finally, the "secure" attribute is a Boolean flag indicating whether a secure HTTP connection is required between the client and server to read the data in the cookie. Usually, this is toggled off. As noted previously, only the first attribute is required; the rest are all optional. If you're using them, remember to separate them with semi-colons, as in the example below:
Now, let's look at writing some code to create a cookie.
blog comments powered by Disqus |