Previous Page
Next Page

Showing Your Cookies

In the previous example, we read the value of one cookie from the server. Now we'll see how to write a script that reads all the cookies that came from your server and displays their names and values. If there are no cookies, the script says "There are no cookies here" (Figure 10.3). If there are cookies, it displays a line per cookie showing what's in the cookie (Figure 10.4). Script 10.5 shows you how.

Figure 10.3. If there are no cookies from the server your Web page is on, you'll see this result.


Figure 10.4. If there are one or more cookies, then the script writes them into the document window.


Script 10.5. This script steps through and displays all of the cookies on your machine that have been set by a particular server.

window.onload = showCookies;

function showCookies() {
     var outMsg = "";

     if (document.cookie == "") {
        outMsg = "There are no cookies here";
     }
     else {
        var thisCookie = document.cookie. split("; ");

        for (var i=0; i<thisCookie.length; i++) {
           outMsg += "Cookie name is '" + thisCookie[i].split("=")[0];
           outMsg += "', and the value is '" + thisCookie[i].split("=")[1] + "'<br />";
        }
     }
     document.getElementById("cookieData"). innerHTML = outMsg;
}

To show all your cookies:

1.
var outMsg = "";



Start by initializing the variable outMsg, which will contain the message we want to display.

2.
if (document.cookie == "") {
  outMsg = "There are no cookies here";



This conditional test is read "If the outMsg object is null (that is, empty), then write, "There are no cookies here" into the document window.

3.
var thisCookie = document.cookie. split("; ");



If the previous test failed (i.e., if there was at least one cookie present), then get the values of all of the cookies using document.cookie.split("; ") and stuff those values into a array called thisCookie. Remember that the split("; ") command creates an array of all of the cookies. Later, the script will be able to reference each of the values in that array.

4.
for (var i=0; i<thisCookie.length; i++) {



This line starts a loop by first setting the value of i, the counter variable, to 0. Then, if i is less than the number of cookies in the thisCookie array, increment the value of i by 1.

5.
outMsg += "Cookie name is '" + thisCookie[i].split("=")[0]);
outMsg += "', and the value is '" + thisCookie[i].split("=")[1] + "'<br />");



As the script moves through the array, it puts the text string "Cookie name is '" into outMsg, followed by the name of the cookie. Then it concatenates the text string "', and the value is '" and the value of the cookie. And at the end of each line, we add an HTML break.

6.
document.getElementById. ("cookieData").innerHTML = outMsg;



After setting the variable outMsg, it gets dumped out to the page via innerHTML when all the cookies have been gone through.


Previous Page
Next Page