Reading Cookies


Now that we've set a cookie, we can read its data back in. That involves using the document.cookie propertythe browser will fill that property with the cookie text for the page that was set earlier automatically.

In the preceding section, we used the setCookie function to set a cookie named cookie1 . When we check that property again (even after reloading the same page), we'll see that document.cookie holds "cookie1=Here is the cookie data!" . Note that this text does not contain the expires =date; pair that we set in the cookie in setCookie , because that pair was intended for the browser itself.

In this example, document.cookie only holds one data pair ( "cookie1=Here is the cookie data!" ), but I'll show how one extracts cookie data in general, even if your cookie contains many such pairs. To retrieve the cookie's data, I'll create a function named getCookie . I start by making a copy of document.cookie so we don't inadvertently change that property. Next I determine the start and end positions of the text that's been assigned to cookie1 (that is, Here is the cookie data! ) by searching for the terminating semicolon that ends cookie data pairs like this (note that if the data you're searching for is at the very end of the cookie string, some browsers omit the final semicolon, which I'm also taking care of in this code):

 function getCookie()  {  var cookieData = new String(document.cookie)   var cookieHeader = "cookie1="   var cookieStart = cookieData.indexOf(cookieHeader) + cookieHeader.length   var cookieEnd = cookieData.indexOf(";", cookieStart)   if(cookieEnd == -1 ) {   cookieEnd = cookieData.length   }  .          .          .  } 

Now we have the starting and ending indices of our data in the cookie string; all that remains is to extract that data itself using the substring method. Here's what that looks like. Note that I'm also handling the case where the cookie was not found (presumably because it was not set or expired ):

 function getCookie()  {      var cookieData = new String(document.cookie)      var cookieHeader = "cookie1="      var cookieStart = cookieData.indexOf(cookieHeader) + cookieHeader.length      var cookieEnd = cookieData.indexOf(";", cookieStart)      if(cookieEnd == -1 ) {          cookieEnd = cookieData.length      }  if (cookieData.indexOf(cookieHeader) != -1){   document.form1.text1.value =   cookieData.substring(cookieStart, cookieEnd)   }   else{   document.form1.text1.value = "Could not find the cookie."   }  } 

Here's an example that puts this code to work, enabling us to retrieve and display the cookie's text in a text field:

(Listing 23-02.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Working With Cookies          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--             function setCookie()              {                  var cookieDate = new Date()                  cookieDate.setTime(cookieDate.getTime() + 24 * 60 * 60 *                      1000)                  document.cookie =                      "cookie1=Here is the cookie data!;expires="                      + cookieDate.toGMTString()                  alert("Cookie created!")              }  function getCookie()   {   var cookieData = new String(document.cookie)   var cookieHeader = "cookie1="   var cookieStart = cookieData.indexOf(cookieHeader) + cookieHeader.length   var cookieEnd = cookieData.indexOf(";", cookieStart)   if(cookieEnd == -1 ) {   cookieEnd = cookieData.length   }   if (cookieData.indexOf(cookieHeader) != -1){   document.form1.text1.value =   cookieData.substring(cookieStart, cookieEnd)   }   else{   document.form1.text1.value = "Could not find the cookie."   }   }  //-->          </SCRIPT>      </HEAD>      <BODY>          <H1>              Working With Cookies          </H1>          <FORM NAME="form1">              <INPUT TYPE = BUTTON Value = "Create the cookie"                  ONCLICK = "setCookie()">              <BR>  <INPUT TYPE="text1" NAME="text1" SIZE="30">   <BR>   <INPUT TYPE = BUTTON Value = "Get the cookie"   ONCLICK = "getCookie()">  </FORM>      </BODY>  </HTML> 

You can see the results in Figure 23.2, where we're reading the text we've assigned to the cookie. Now we're using cookies. Note that you can set the cookie in one session, close the browser, open it again, load the same page, and click the "Get the cookie" button to read and see the cookie's data (so long as the cookie hasn't expired, of course).

Figure 23.2. Reading cookie data.

graphics/23fig02.gif

Now we've set a cookie and read it back in, deciphering its data. But what about cookie maintenance? Can you delete cookies when you want to? I'll take a look at that in the next section.



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net