Java Reference
In-Depth Information
In the next if statement, you check to see whether the cookie has been found. If it hasn't, you set
the value variable to null :
if (cookieStartsAt == -1) {
value = null;
}
If the cookie has been found, you get the value of the cookie you want from the document
.cookie string in an else statement. You do this by finding the start and the end of the value part
of that cookie. The start will be immediately after the equals sign following the name. So in the
following line, you find the equals sign following the name of the cookie in the string by starting
the indexOf() search for an equals sign from the character at which the cookie name/value pair
starts:
else {
cookieStartsAt = value.indexOf("=", cookieStartsAt) + 1;
You then add one to this value to move past the equals sign.
The end of the cookie value will either be at the next semicolon or at the end of the string, whichever
comes first. You do a search for a semicolon, starting from the cookieStartsAt index, in the next
line:
var cookieEndsAt = value.indexOf(";", cookieStartsAt);
If the cookie you are after is the last one in the string, there will be no semicolon and the
cookieEndsAt variable will be ‐1 for no match. In this case you know the end of the cookie value
must be the end of the string, so you set the variable cookieEndsAt to the length of the string:
if (cookieEndsAt == -1) {
cookieEndsAt = value.length;
}
You then get the cookie's value using the substring() method to cut the value that you want out
of the main string. Because you have encoded the string with the escape() function, you need to
unescape it to get the real value, hence the use of the unescape() function:
value = unescape(value.substring(cookieStartsAt,
cookieEndsAt));
Finally, you return the value of the cookie to the calling function:
return value;
What's New?
trY it out
Now you know how to create and retrieve cookies. Let's use this knowledge in an example in which
you check to see if any changes have been made to a website since the user last visited it.
You'll be creating two pages for this example. The first is the main page for a website; the second is the
page with details of new additions and changes to the website. A link to the second page will appear on
Search WWH ::




Custom Search