Java Reference
In-Depth Information
Okay, so now you know that cookies are specific to a certain path, but what if you want to view
your cookies from two different paths on your server? Say, for example, you have an online store at
pages in the
/Checkout
directory. To get around this you can either set cookies only in the
/mystore
directory (because these can be read by that directory and any of its subdirectories), or you can use
the
path
part of the cookie string to specify that the path of the cookie is
/mystore
even if it's being
set in the
/Games
or
/Books
or
/Checkout
subdirectories.
For example, you could do this like so:
document.cookie = "UserName=Paul;expires=Tue, 28 Dec 2020 00:00:00" +
";path=/mystore;";
Now, even if the cookie is set by a page in the directory
/Books
, it will still be accessible to files in
the
/mystore
directory and its subdirectories, such as
/Checkout
and
/Games
.
If you want to specify that the cookie is available to all subdirectories of the domain it is set in, you
can specify a
path
of the root directory using the
/
character:
document.cookie = "UserName=Paul;expires=Tue, 28 Dec 2020 00:00:00;path=/;";
Now, the cookie will be available to all directories on the domain it is set from. If the website is just
one of many at that domain, it's best not to do this because everyone else will also have access to
your cookie information.
It's important to note that although Windows computers don't have case‐sensitive directory names,
many other operating systems do. For example, if your website is on a Unix‐ or Linux‐based server,
the
path
property will be case‐sensitive.
domain
The fourth part of the cookie string is the
domain
. An example of a domain is
wrox.com
or
beginningjs.com
. Like the
path
part of the cookie string, the
domain
part is optional and it's
unlikely that you'll find yourself using it very often.
By default, cookies are available only to pages in the domain in which they were set. For example, if
you have your first website running on a server with the domain
mypersonalwebsite.mydomain
.com
and you have a second website running under
mybusinesswebsite.mydomain.com
, a cookie
set in one website will not be available to pages accessed under the other domain name, and vice
versa. Most of the time, this is exactly what you want, but if it is not, you can use the
domain
part
of the cookie string to specify that a cookie is available to all subdomains of the specified domain.
For example, the following sets a cookie that can be shared across both subdomains:
document.cookie = "UserName=Paul;expires=Tue, 28 Dec 2020 00:00:00;path=/" +
";domain=mydomain.com;";