Java Reference
In-Depth Information
A lot of different ways exist to get the value of an individual cookie, but the way you'll use has the
advantage of working with all cookie‐enabled browsers. You use the following function, which you
need to add to your cookiefunctions.js ile:
function getCookieValue(name) {
var value = document.cookie;
var cookieStartsAt = value.indexOf(" " + name + "=");
if (cookieStartsAt == -1) {
cookieStartsAt = value.indexOf(name + "=");
}
if (cookieStartsAt == -1) {
value = null;
} else {
cookieStartsAt = value.indexOf("=", cookieStartsAt) + 1;
var cookieEndsAt = value.indexOf(";", cookieStartsAt);
if (cookieEndsAt == -1) {
cookieEndsAt = value.length;
}
value = unescape(value.substring(cookieStartsAt,
cookieEndsAt));
}
return value;
}
The first task of the function is to get the document.cookie string and store it in the value variable:
var value = document.cookie;
Next, you need to find out where the cookie with the name passed as a parameter to the function
is within the value string. You use the indexOf() method of the String object to find this
information, as shown in the following line:
var cookieStartsAt = value.indexOf(" " + name + "=");
The method will return either the character position where the individual cookie is found or ‐1 if no
such name, and therefore no such cookie, exists. You search on " " + name + "=" so that you don't
inadvertently find cookie names or values containing the name that you require. For example, if you
have xFoo , Foo , and yFoo as cookie names, a search for Foo without a space in front would match
xFoo first, which is not what you want!
If cookieStartsAt is ‐1 , the cookie either does not exist or it's at the very beginning of the cookie
string so there is no space in front of its name. To see which of these is true, you do another search,
this time with no space:
if (cookieStartsAt == -1) {
cookieStartsAt = value.indexOf(name + "=");
}
Search WWH ::




Custom Search