Cookies


Cookiesyou either love them or hate them. Programmers are not usually on the hate-them side, because cookies help the programming process a great deal by enabling you to store data that the browser environmenta notoriously ephemeral environmentcan use. You can customize the appearance of your web site for particular users with cookiesfetching and displaying economic data, for example, or setting background coloror store the data associated with a single session but multiple pages.

From the users' point of view, however, you're storing data on their computer. Worse, they have no control over that data. Although cookies have largely been accepted now, there continue to be security issues, including cases of hackers being able to store code in cookies that is executed by the browser (although security holes like this are patched vigorously by browser manufacturers when discovered ).

The actual cookie stored by JavaScript code is just text, and it's stored in the document.cookie property. This makes accessing cookies very easy, as we'll see. The actual cookie text itself is made up of name =value; pairs. (Each pair is sometimes called a crumb , and each should end with a semicolon.) If you want to store a value of 555 as a cookie's ID, for example, you might use a pair like this id=555; . In JavaScript, you can store up to 20 such pairs in a single cookie string.

Some pairs are already interpreted by the browser, including the following:

  • expires =date; sets the expiration date for the cookie. Use GMT format to specify the date. Note that not setting expiration date for a cookie will make it to expire when the browser is closed. On the other hand, if you set an expiration date for sometime in the future, the cookie is saved until then. If you set an expiration date in the past, however, the cookie is deleted.

  • domain=domainname; sets a cookie's domain. This isn't often usedsetting the domain of the cookie lets pages from one domain that is made up of multiple servers share a cookie.

  • path= path ; sets a cookie's path. Setting a path for the cookie allows the current page to share cookie information with other pages from the same domain, because cookies are stored according to path.

  • secure; makes a cookie secure. Making a cookie secure means the cookie information can be read or set only in a secure environment.

The browser stores only one cookie per page. When you reload that page, the browser determines which cookie to give you access to by seeing what page (including the path of that page) you've loaded, and you'll get the whole cookie text for that page in the document.cookie property. You have to search that cookie text for the data pair you want yourself.

Let's take a look at an example.



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net