1. |
This script is going to keep track of how many cookies we've deleted, so we start off by creating the cookieCt variable and setting it to zero.
|
2. |
if (document.cookie != "" && confirm("Do you want to delete the cookies?")) {
This test first checks to make sure that the cookie doesn't contain a null value, that is, there are some cookies. If the test shows that the cookie is empty, then the script will do nothing. The second part of the test tells the browser to put up a confirmation dialog with the included text ( Figure 10.6). If confirm() returns true, then we know the user wants to delete their cookies. If false, then we skip down to step 9.
|
3. |
var thisCookie = document.cookie. split("; ");
This line splits the contents of the cookie into an array with the split("; ") method and assigns that array to the variable thisCookie.
|
4. |
cookieCt = thisCookie.length;
We now know how many cookies we're going to be deleting, so that's stored in cookieCt.
|
| |
5. |
var expireDate = new Date();
expireDate.setDate(expireDate. getDate()-1);
Here we create a new date object, expireDate, which is then set to the current date minus 1in other words, to yesterday.
|
6. |
for (var i=0; i<cookieCt; i++) {
Now begin a for loop, so that we can delete all the cookies, not just one. First set the value of i to 0; then, as long as i is less than the number of cookies, increment i by 1.
|
7. |
var cookieName = thisCookie[i]. split("=")[0];
Use split("=")[0] to get the name of the i th cookie in the array, which is then stored in the variable cookieName.
|
8. |
document.cookie = cookieName + "=;expires=" + expireDate. toGMTString();
Here's where the cookie with the changed expiration date gets written back out.
|
9. |
document.getElementById ("cookieData").innerHTML = "Number of cookies deleted: " + cookieCt;
The script is out of the for loop now, and this line sets the number of cookies deleted in the HTML document ( Figure 10.7).
|