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 needs
to be added to your CookieFunctions.js fi le:
function getCookieValue(cookieName)
{
var cookieValue = document.cookie;
var cookieStartsAt = cookieValue.indexOf(“ “ + cookieName + “=”);
if (cookieStartsAt == -1)
{
cookieStartsAt = cookieValue.indexOf(cookieName + “=”);
}
if (cookieStartsAt == -1)
{
cookieValue = null;
}
else
{
cookieStartsAt = cookieValue.indexOf(“=”, cookieStartsAt) + 1;
var cookieEndsAt = cookieValue.indexOf(“;”, cookieStartsAt);
if (cookieEndsAt == -1)
{
cookieEndsAt = cookieValue.length;
}
cookieValue = unescape(cookieValue.substring(cookieStartsAt,
cookieEndsAt));
}
return cookieValue;
}
The fi rst task of the function is to get the document.cookie string and store it in the variable
cookieValue.
var cookieValue = document.cookie;
Next, you need to fi nd out where the cookie with the name passed as a parameter to the function is
within the cookieValue string. You use the indexOf() method of the String object to fi nd this infor-
mation, as shown in the following line:
var cookieStartsAt = cookieValue.indexOf(“ “ + cookieName + “=”);
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 “ “ + cookieName + “=” so that you
don't inadvertently fi nd 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 fi rst, 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)
{
Search WWH ::




Custom Search