CIT041J Index > Lecture Notes - Cookies

CIT041J Lecture Notes - Cookies (page 2)

Retrieving Cookie Information

We want to retrieve the cookie as soon as the page starts to load, so we will put the code right in the <head> section of the page. We will use the split() method, which takes a string and splits it into pieces delimited by a given character. Example:

Thisis equivalent to
var str = "cat/dog/fish";
var words =
 str.split( "/" );
var words = new Array(
   "cat", "dog", "fish"
);

The document.cookie string has the general format:

name1=value1; name2=value2

We need to split the document.cookie with semicolon-and-blank as the delimiter. The following code will create an associative array with the cookie names as the index and the values as the array contents. The first split() call will split the cookie into name-value pairs. Thus, pairs[0] will be the string name1=value1 and pairs[1] will be name2=value2. We then split each pair on = to separate the name and value. We then have to use the unescape() function to URL-decode the value.

var cookieInfo = new Array(); // an associative array
function getCookieInfo()
{
    var pairs = document.cookie.split("; ");
    var onePair;
    var i;
    var cookieName, cookieValue;
    for (i=0; i < pairs.length; i++)
    {
        onePair = pairs[i].split("=");
        /* onePair[0] is the cookie name; onePair[1] is the cookie value */
        cookieName = onePair[0];
        cookieValue = unescape( onePair[1] );
        cookieInfo[cookieName] = cookieValue;
    }
}

On the previous, we asked for the user’s name and set a cookie in the form

yourName=user_input
We’d like to extract that user name and display it in the body of a page. Along with the getCookieInfo(), which retrieves all cookies, we will add this function, which retrieves a single cookie value by its name:

function getCookieValue( desiredName )
{
    var pairs
    var nameAndValue;
    var i;
    var result = null;
    
    if ( document.cookie )
    {
        pairs = document.cookie.split("; ");
        for (i = 0; i < pairs.length && result == null; i++)
        {
            nameAndValue = pairs[i].split("=");
            if (desiredName == nameAndValue[0])
            {
                result = unescape(nameval[1]);
            }
        }
    }
    return result;
}

Now we call the function (while still in the head of the document) to put the value into a global variable.

var theName = getCookieValue( "yourName" );

And then we can use that by putting it into a document.write() to produce a personalized page for .