Free Web tutorials covering HTML, CSS, JavaScript, and DHTML from beginner to advanced. Free downloads and developer resources. Personalized help via email, form, and chat.

free, web, tutorials, HTML, html, CSS, css, stylesheet, cascading stylesheet, Javascript, javascript, JavaScript, DHTML, dhtml, beginner, advanced, web development, web page, web site, free web tutorial, free HTML tutorial, free CSS tutorial, free css tutorial, free cascading stylesheet tutorial, free stylesheet tutorial, free javascript tutorial, free DHTML tutorial, free HTML class, free CSS class, free stylesheet class, free cascading stylesheet class, free javascript class, free DHTML class">

Free Web tutorials covering HTML, CSS, JavaScript, and DHTML from beginner to advanced. Free downloads and developer resources. Personalized help via email, form, and chat. free, web, tutorials, HTML, html, CSS, css, stylesheet, cascading stylesheet, Javascript, javascript, JavaScript, DHTML, dhtml, beginner, advanced, web development, web page, web site, free web tutorial, free HTML tutorial, free CSS tutorial, free css tutorial, free cascading stylesheet tutorial, free stylesheet tutorial, free javascript tutorial, free DHTML tutorial, free HTML class, free CSS class, free stylesheet class, free cascading stylesheet class, free javascript class, free DHTML class

<Code_Punk>'s

Advanced JavaScript Lesson 31:
Cookie Detection & Cookie Killing

Code Tutorials



Site Development



Downloads



Help!!



Home


Simple Detection

In most cases where cookies are used, the page reading the cookie appears before the page writing the cookie. Here's an example of such a page. The page you see first reads the cookie, if one is present. It has to run a script to tell it if there is a cookie available to read or not.

NOTE: If the example shows some weird looking data, click the "Kill Cookie" link until it disappears and then continue. What you're seeing is the data from previous example's cookies that were set on your machine, but haven't expired.

This is critical in many cookie applications. If there is no cookie, JavaScript variables meant to be assigned values by a cookie will have no value and cause errors (missing object type errors). On the other hand, if the cookie exists, then data from the cookie can be used.

Such is the case with our example. The page uses a JavaScript "document.write()" variable to write a name. If that variable has no value assigned to it, the page will cause an error. If there is no cookie set, there will be no value to assign the variable. So, I used cookie detection to assign a "stub", or meaningless, value to the variable if no cookie is present. I also make sure that the display of stub value(s) is not visible (and ugly).

Cookie detection uses the IF/ELSE statements. The simplest form of cookie detection is:

if (document.cookie){
CODE IF COOKIE EXISTS}

else{
CODE IF COOKIE DOES NOT EXIST}

The above checks for any cookie set by your domain (site). You might read elsewhere that if (document.cookie) only refers to the browsers ability to handle cookies - whether or not cookie support is enabled. This is not true.

Using if (document.cookie) detects any cookie that can be read by the page detecting cookies. It will detect any cookie that is available to the page. We can narrow this down, however, by adding to our IF statement.

More Detection

Cookie detection can be more specific. It can check for cookies with no value:

if (document.cookie && document.cookie != "")

The above tests for both the presence of a cookie and that the cookie isn't a blank string (""), or "null".

We can also use "indexOf()" to search the cookie for specific strings to make sure we're reading the right cookie. We'll go into this in more detail when studying multiple cookies. Basically, it goes like this:

if (document.cookie && document.cookie.indexOf("search_string") > -1)

In practice, a little more processing must be done to get the above to work, but you get the idea. We'll deal with this in detail when we study multiple cookies.

The possibilities of detecting data on a cookie are nearly endless. Any test or operation used on a text string can be applied to "document.cookie".

Placing The Code

Cookie detection goes in the <head>'s <script> section of the page detecting the cookie. It is placed outside any function in most cases. This is because the cookie must be detected (or not) and variables assigned before the page loads in most cases. Some sites redirect to a cookie setting page automatically (window.location), before the current cookie reading page loads, if no cookie is found.

In our example, the variable "client_name" must have an assigned value before the page loads or an error will occur. Here's the detection code for the first page of our example:

<script language="JavaScript">

if (document.cookie && document.cookie != ""){

var client_name1 = document.cookie);
var client_name2 = client_name1.split("=");
var client_name = unescape(client_name2[1]);
}

else {client_name = "stub";}

First the cookie was detected with if (document.cookie...). Next, I wanted to make sure that the cookie was not blank, or null.

The important thing to note is that most cookie detection schemes exist to give needed variables values if the cookie is not present. In the above I process the cookie's data into the needed value for "client_name". If the cookie did not exist, the ELSE statement would assign "client_name" a default (or stub) value. I used the string "stub" for this default value.

Either way, "client_name" will have a value and the page will not cause errors. I can now use if (client_name == "stub") in later functions to see if a real "client_name" from the cookie (not a cookie itself) exists or not.

Also note that I went ahead and processed the "client_name" value in my cookie detection. You could do this in a function later, but it's more trouble than just going ahead and assigning values directly in the cookie detection script. Cookie detection and variable assignments go hand-in-hand.

Notice that the second page, the one setting the cookie, validates the cookie's data to make sure a name is entered before the cookie is written. Good validation before the cookie is written greatly simplifies detection and variable assignment schemes. In short, do your data validation and testing before writing the cookie on the page that sets the cookie.

A popular alternative to assigning stub values to variables is to simply redirect the "non-cookie" viewer to the page that sets the cookie. This redirect occurs before the page needing the cookie data loads, thus preventing errors from unassigned variables.

Killing A Cookie

There are a number of reasons you'd want to "kill" or delete one of your cookies from your viewers' browser cache. I made a link to kill the cookie in the example so you could clear the cookie and start again.

Sometimes you change your cookie. You add data and reformat the data you're writing to the cookie. In these cases, you'd want to kill your old cookies before cookie detection so the old cookie won't be used.

You'll be using cookie killing a lot when experimenting with cookies. It allows you to delete and retry cookies even if an expiration date has been set and without having to close and reopen your browser.

The key to killing cookies lies in the expiration date. If you reset the cookie's expiration date to any time in the past, the cookie will delete itself. It's expiration date has passed.

You must remember the "name" you gave the cookie. This is what you set the value to:

document.cookie = "name=cookie_data";

Resetting the expiration date to kill a cookie is done in three steps. First, make a new date object and set it to any date in the past. Secondly, convert the date to the proper format (GMT). Finally, add a string including the new expiration date and set the cookie. Here's step 1:

var kill_time = new Date("January 1, 1970");

This creates a date object for 1 January 1970. You can use any date in the past. I was too lazy to put this in the fancy format used by cookies. Cookies will accept a full Date() object or one converted to GMT (Greenwich Mean Time). This is the time in Greenwich, England and is considered the time standard because those good folks came up with longitude and the global time scheme used today.

You don't have to worry about doing this formatting manually. JavaScript has a "toGMTString()" method that you can apply to any Date() object. This will format the time string for you. You can apply the "toGMTString()" method right in the cookie's string. So, step 2 is:

var kill_time = new Date("January 1, 1970");
var kill_string = "client_name=stub;expires=" + kill_time.toGMTString();

Pay particular attention to the capitalization of the "toGMTString()" method. Many mistakes are made here.

Now this cookie string is set with "document.cookie" and the cookie will immediately kill itself.

var kill_time = new Date("January 1, 1970");
var kill_string = "client_name=stub;expires=" + kill_time.toGMTString();
document.cookie = kill_string;

It is important to note that this will only kill a cookie named "client_name=". Cookies with data set to another name will not be killed. The data assigned to the name makes no difference because the cookie will be deleted, but the name itself is very important. It determines which cookie you want deleted. We'll get into this more when we study using multiple cookies.

Summary & Review

Cookie detection is needed to find out if your cookie exists or not. Many pages reading cookies are viewed before the page setting a cookie. This can cause trouble because cookie data is used to assign values to JavaScript variables on the cookie reading page. If these variables are left unassigned (because there is no cookie), errors will occur as the page loads.

The simplest cookie detection is done with IF (document.cookie). We'll discuss more sophisticated methods in later tutorials. If the cookie exists, we can go ahead and process it's data into variable values. If no cookie exists, we can assign "stub" values to our variables to prevent errors. This is done in an ELSE statement.

As an alternative to assigning stub values, you can redirect a viewer with no cookie to the page that sets the cookie before the cookie reading page loads.

Validate your cookie's data before writing the cookie to the viewer's hard drive. This saves a lot of parsing later when the cookie reading page loads.

You can "kill" a cookie by setting its expiration date to any time in the past. You can change the date of a cookie by using "new Date(sometime in the past)" to make a "past" date object and "toGMTString()" to convert the past Date() object to the proper format for cookies. Now just assign a string with a past date to the cookie with "document.cookie".

When killing a cookie, make sure to use the same name ([cookie_name] = cookie data;expires=[expiration date]) as the cookie you want killed. Only the approprately named cookie will be overwritten with the "kill" date.

For practice, make the example pages from scratch comparing them to the example here. Next, add more data to your cookie, say a hobby or last name or email address. Validate and add this data to the string demarcating the values with "xxx" or ":::" or whatever as per Lesson 28 - Parsing Cookie Data.

Remember that only the data string in the cookie needs to be "escape()d" and "unescape()d". Not the whole string:

Escaping cookie data when writing:

"cookie_name=" + escape(cookie_data) + "; expires=" + expiration_date;

Unescaping cookie data that has been read can occur after the data has been separated from the cookie's name (cookie_name) or right as the cookie is read.

Like this:

var all_cookie_data = document.cookie;
var cookie_chunks = all_cookie_data.split("=");
var data_to_use = unescape(cookie_chunks[1]);

OR - I like this one.

var all_cookie_data = unescape(document.cookie);
var cookie_chunks = all_cookie_data.split("=");
var data_to_use = cookie_chunks[1];



To Next Advanced JavaScript Lesson

Back To Advanced JavaScript Index