Last Updated:

Use of cookies - JavaScript

Cookies are the only way that allows server extensions and JavaScript to store some data on the hard drives of client computers for a long time. Generally speaking, a cookie is a property of an HTML document. Cookie data is physically stored locally on the computer of the user who downloaded this document, in the form of a special system file.

The easiest way to think of a cookie is as a set of string parameters, each with a name and a value. JavaScript can create a cookie on an HTML document by defining an arbitrary number of parameters in the HTML document and setting arbitrary values for them. Once created, this set of parameters becomes the property of that particular HTML document and can be parsed, modified, or deleted by JavaScript.

The main purpose of a cookie is to give the user the ability to customize the interface of active HTML documents to suit their needs. In addition, cookies are widely used to support session connections of various server applications, such as e-mail systems, online stores, Internet games.

 

Perform basic operations with cookies

 

Without going into the details of how data is stored in cookies, let's look at the basic functions that allow JavaScript scripts to set cookie values, read and delete previously set values.

 

Creating a cookie - addCookie

This feature allows JavaScript to set cookie values for HTML pages.

function addCookie(szName,szValue,dtDaysExpires) 
{
   var dtExpires = new Date();
   var dtExpiryDate = "";

   dtExpires.setTime(dtExpires.getTime() + 
     dtDaysExpires * 24 * 60 * 60 * 1000);

   dtExpiryDate = dtExpires.toGMTString();

   document.cookie = 
    szName + "=" + szValue + "; expires=" + dtExpiryDate;
}

This addCookie function gets three parameters. The szName parameter passes the name of the parameter stored in the cookie. The szValue parameter specifies the value of this cookie parameter. The dtDaysExpires parameter is the number of days after which the generated cookie must be deleted.

For example, the following line creates a cookie named Count with a value of 0, and after 10 days the browser will automatically delete this cookie:

addCookie("Count","0",10);

 

Get the cookie value - findCookie

Below is the text of the function that allows you to read the meaning of a previously created cookie.

function findCookie(szName) 
{
  var i = 0;
  var nStartPosition = 0;
  var nEndPosition = 0;  
  var szCookieString = document.cookie;  

  while(i <= szCookieString.length) 
  {
    nStartPosition = i;
    nEndPosition = nStartPosition + szName.length;

    if(szCookieString.substring( 
        nStartPosition,nEndPosition) == szName) 
    {
      nStartPosition = nEndPosition + 1;
      nEndPosition = 
        document.cookie.indexOf(";",nStartPosition);

      if(nEndPosition < nStartPosition)
        nEndPosition = document.cookie.length;

      return document.cookie.substring( 
          nStartPosition,nEndPosition);  
      break;    
    }
    i++;  
  }
  return "";
}

With this function, firstly, you can check whether a cookie with a given name is set for this document: Secondly, this function allows you to write the value of the cookie parameter with the specified name into a text variable:

if(findCookie("Visit") == "")
{
  // cookie с  Visit не установлен
  . . .
}
else
{
  // cookie с  Visit установлен
  . . .
}
var szVisitValue = findCookie("Visit");

 

Deleting cookies - removeCookie

The removeCookie function deletes previously created cookies:

function removeCookie(szName) 
{
  var dtExpires = new Date();
  dtExpires.setTime(dtExpires.getTime() - 1);

  var szValue = findCookie(szName);

  document.cookie = szName + "=" + szValue +
    "; expires=" + dtExpires.toGMTString();
}

Examples of the use of cookies

As an example of the use of cookies, consider the counter of visits of some HTML page. Note that this will be a local counter that displays the number of visits from this particular computer. The total number of visits can only be determined by using server applications.

Listing 7.1.

<HTML>
  <HEAD>
    <TITLE>Cookies demo</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    function addCookie(szName,szValue,dtDaysExpires)
    {
      var dtExpires = new Date();
      var dtExpiryDate = "";

      dtExpires.setTime(dtExpires.getTime() +
        dtDaysExpires * 24 * 60 * 60 * 1000);

      dtExpiryDate = dtExpires.toGMTString();

      document.cookie =
        szName + "=" + szValue + "; expires=" +
        dtExpiryDate;
    }

    function findCookie(szName)
    {
      var i = 0;
      var nStartPosition = 0;
      varnEndPosition = 0;
      var szCookieString = document.cookie;

      while (i<=szCookieString.length)
      {
        nStartPosition = i;
        nEndPosition = nStartPosition + szName.length;

        if(szCookieString.substring( nStartPosition,nEndPosition) == szName)
        {
          nStartPosition = nEndPosition + 1;
          nEndPosition = document.cookie.indexOf(";",nStartPosition);

          if(nEndPosition < nStartPosition)
            nEndPosition = document.cookie.length;

          return document.cookie.substring( nStartPosition, nEndPosition);
          break;
        }
        i++;
      }
      return "";
    }

    functionNewCount()
    {
      if(findCookie("Count") == "")
      {
        addCookie("Count","0",10);
      };
      var szCnt = findCookie("Count");
      var i=0;
         i = szCnt;
         i++;
         szCnt = i.toString();
         addCookie("Count",szCnt,10);
      document.write(szCnt);
    }
    // -->
    </SCRIPT>
  </HEAD>
  <BODY BGCOLOR=white>
    <H1>Welcome!</H1>
    You are already visiting our page <b>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
      NewCount();
    // -->
    </SCRIPT>
    </b>th time!

  </BODY>
</HTML>