JavaScript : Smart Sites and Cute Cookies
Contents ]
Dr Benton

Function for Reading a Cookie

The function litCookie will look for our cookie among all those which have been saved on the visitor's computer and will read its content:

function litCookie(nom)
{
  var rechercher = new String(nomCookie + "=" + nom);
  if (document.cookie.length > 0)       // Are there any cookies?
  {
    debut = document.cookie.indexOf(rechercher);
    if (debut != -1)                    // Does the cookie exist?
    {
      fin =  debut + rechercher.length; // End of string
      if (fin == -1) fin = document.cookie.length;
      compteur_debut = fin + 3;
      compteur_fin = document.cookie.lastIndexOf("%");
      nombreVisites = document.cookie.substring(compteur_debut, compteur_fin);
      nombreVisites++;
      miseAJour(nom);
      return unescape(document.cookie.substring(debut, fin));
    }
    else return "";
  }
  else return "";
}

First we look for the beginning of the cookie to distinguish the name from the number of visits. Once this number is found, retrieved and stored in the variable nombreVisites, it is incremented by 1 and the function miseAJour() is called up. This modifies the cookie to update the number of times the visitor came onto the site.

Note that if no cookie exists on the visitor's computer (document.cookie.length = 0), or if the start of the cookie is not found (document.cookie.indexOf(rechercher) = -1), the function will return an empty string (else return "";).

Our function also handles character strings, which give us the opportunity to find out about some of the methods of the String object:

  • chaine.lastIndexOf(param) searches the character string chaine for the string param, starting from the right, and returns the position as an integer.

  • Example: with chaine = "Hello friend Hello" and param = "Hello"; the returned value is 14.

  • chaine.indexOf(param) : same as before but here the search starts from the left.

  • The same example would return 1.

  • chaine.substring(debut,fin) returns as a string the characters of chaine enclosed between the starting and ending positions specified in debut and fin respectively.

  • With the same value in chaine as in the previous examples and the values 7 and 12 for the debut and fin parameters, the method would return the string "friend".



  1   2   3   4   5   6   7