Java Reference
In-Depth Information
Cookies are small files that are saved locally on a user's computer. They were invented
by Netscape as a way of getting round HTTP being a stateless protocol. This means that
a browser does not remember anything from one request to another. So every time a user
visits a page, nothing about any previous visits is remembered. Cookies can be used to
sidestep this problem by storing information that can then be retrieved between requests.
A restriction of cookies is that they can only be read by a web page from the same domain
that set them. This is to stop sites being able to access information about users, such as oth-
er sites they have visited. Cookies are also limited to storing up to 4KB of data, although
20 cookies are allowed per domain, which can add up to quite a lot of data.
Cookies can be used for personalising a user's browsing experience, storing user prefer-
ences, keeping track of user choices (such as a shopping cart), authentication and tracking
users. The use of cookies for tracking purposes has been much maligned in recent years.
Their use for data storage is starting to be replaced in many cases by the new HTML5 loc-
alStorage API as it allows more data to be stored; this is covered in Chapter 14. Cookies
are still useful for retaining state information (such as if a user is logged in) because they're
passed between the client and server on every HTTP request.
Cookies take the form of a text file that contain a list of name/value pairs separated by
semicolons. For example, a cookie file might contain the following information:
"name=Superman; hero=true; city=Metropolis"
Creating Cookies
To create a cookie, you assign it to JavaScript's “cookie jar,” the document.cookie
property, like so:
document.cookie = "name=Superman"
<< "name=Superman"
The document.cookie property acts like a special type of string. Assigning another
cookie to it won't overwrite the entire property, it will just append it to the end of the string.
So we can add more cookies by assigning them to document.cookie :
Search WWH ::

Custom Search