14.2 Creating a Cookie with JavaScript

In the following examples, we will create a cookie, view the cookie, and then destroy it. It is important to note when you are setting cookies that they are stored in the browser's memory and not written to the hard drive until you exit the browser.

14.2.1 The Cookie Object

The cookie is stored by JavaScript as a document object for both reading and writing cookie data. Cookies are made by assigning attributes to the cookie property. When you start your browser, if there are cookies, they pertain to the current document. The document.cookie property contains a string of name =value pairs representing the names of all the cookies and their corresponding values, such as a session ID number or a user ID. All the other attributes set for the cookie, such as expiration date, path , and secure, are not visible. In a JavaScript program, if you execute the statement shown in Figure 14.3, you will see all the cookies set for this page.

Figure 14.3. Using alert(document.cookie);.


When you reload the page, the document.cookie property will contain all the cookie text saved for that page.

14.2.2 Assigning Cookie Attributes

To create a cookie, assign the name=value pairs to the document.cookie property. Be careful with quotes, making sure the variables you use are not quoted, but the text that the cookie needs, such as the word "name" , and "=" are quoted. Also, this will be a big string where the different parts are concatenated together with the + operator. The following format sets a cookie using all possible attributes. Those attributes enclosed in square brackets are optional:




 document.cookie="id=" + form1.cookie.value ";expires=" + expiration_date+";path=/"; 
The escape() and unescape () Built-In Functions

It is important to know that when assigning string name=value attributes to a cookie, you cannot use whitespace, semicolons, or commas. The escape() function will encode the string object by converting all non- alphanumeric characters to their hexadecimal equivalent, preceded by a percent sign; for example, %20 represents a space and %26 represents an ampersand. In order to send information back and forth between browser and server, the browser encodes the data in what is called URI encoding. You can see this encoding in the location bar of your browser; when you go to Google and search for something, you will see the search string in the location bar of the browser all encoded. Since the browser handles cookies, the cookie strings can be encoded with JavaScript's built-in escape() function to ensure that the cookie values are valid.

The unescape() function converts the URI-encoded string back into its original format and returns it. The encodeURI() and decodeURI() built-in functions are a more recent version of escape() and unescape() and do not encode as many characters.

Example 14.1
 <html><head><title>The escape() Method</title>     </head><center><h2>URL Encoding </h2>     <script language="JavaScript"> 1  function seeEncoding(form){  var myString = form.input.value; 2           alert(  escape(myString  ));         } 3  function seeDecoding(form)  {             var myString = form.input.value; 4           alert(  unescape(myString)  );         }     </script>     <body background="cookebg.jpg" >     <form name="form1">          Type in a string of text:         <p>         <input type="text" name="input" size=40>         <p>         <input type="button"             value="See encoding" 5  onClick="seeEncoding(this.form);  ">         <p>         <input type="button"             value="See decoding" 6  onClick="seeDecoding(this.form);  ">         <p>     </form>     </center>     </body>     </html> 


  1. A function called seeEncoding() is defined. It takes a reference to a form as its only parameter.

  2. The built-in escape() function is used to URI encode the string that was entered as input by the user.

  3. A function called seeDecoding() is defined. It takes a reference to a form as its only parameter.

  4. The built-in unescape() function is used to convert the URI encoded string back into its original ASCII format.

  5. When the user clicks this button, the onClick event is triggered and the encoded string will appear in an alert dialog box.

  6. When the user clicks this button, the onClick event triggers a function that will decode the encoded string. See Figures 14.4 and 14.5.

    Figure 14.4. Using the escape() and unescape() functions.


    Figure 14.5. The user pressed the "See encoding" button (top); the user pressed the "See decoding" button (bottom).


14.2.3 Let's Make a Cookie!

Now that we have all the ingredients , let's put them together and make a cookie, then pull it out of the oven (your program) and voila! a delicious cookie for your browser. The following example creates a cookie called "name" . The value assigned to it will be the user's name. You will see this name=value pair in the document.cookie property.

Example 14.2
 <html><head><title>Making a Cookie</title>     <script language="JavaScript"> 1  function makeCookie(form)  { 2       var when = new Date();         when.setTime(when.getTime() + 24 * 60 * 60 * 1000);  // 24 hours from now  3       when.setFullYear(when.getFullYear() + 1);                                          //  One year from now  yname=form.yourname.value; 4  document.cookie=escape("name")+"="+escape(yname)+   ";expires="+when.toGMTString();  alert(document.cookie);     } 5  function welcome(myForm){  you=myForm.yourname.value; 6       var position=document.cookie.indexOf("name=");         if ( position != -1){             var begin = position + 5;             var end=document.cookie.indexOf(";", begin);             if(end == -1){ end=document.cookie.length;} 7  you= unescape(document.cookie.substring(begin, end));  8  alert("Welcome " + you);  }         else{ alert("No cookies today");}     }     </script>     </head>     <body background="cookiebg.jpg" onLoad="document.form1.reset()" >     <center>     <h2> Got milk?</h2>     <form name="form1">         What is your name?         <br> 9       <input type="text" name="yourname" >         <p> 10      <input type="button" value="Make cookie"             onClick="  makeCookie(this.form)  ;">             <p> 11      <input type="button"             value="  Get Cookie" onClick="welcome(this.form);  ">         <p>     </form>     </body>     </html> 


  1. A function called makeCookie() is defined. It takes a reference to a form as its only parameter. This is the function that creates the cookie.

  2. A new Date object is created and assigned to the variable called when .

  3. The Date object creates a date a year from now. This will be the expiration date for the cookie.

  4. The cookie is created. Its name is "name" and its value is the user's name, stored in yname . The attributes are escaped just in case the user added unwanted characters, such as spaces, commas, or semicolons. The expiration date is set to a year from now and is converted to GMT time, the required format for the "expires" attribute. Notice the quotes. If the text is literal for the attribute it must be quoted; if it is a variable value, then it is not quoted or JavaScript can't interpret it ”very tricky getting these right.

  5. A function called welcome() is created. It takes a reference to a form as its only parameter. Its purpose is to greet the user based on the cookie value.

  6. The following statements are used to parse out the value attribute of the cookie. The beginning index position is set to where the "name=" string starts in the cookie string. It will be at position 5 in this example. Starting at index position 0, position 5 takes us to the character directly after the = sign. The end position is either at the first semicolon or at the end of the string, whichever applies.

  7. After getting the substring, the value part of the cookie, the unescape() function, will convert the URI-encoded string back into its original ASCII format.

  8. The user is welcomed, all based on the value extracted from the cookie. The cookie lets Web sites know who you are so that you can get a personal greeting when you return to the site.

  9. The user will enter his name in a text box field. See Figure 14.6.

    Figure 14.6. Making a cookie.


  10. When the user clicks this button, the onClick event is triggered, and the cookie will be made. See Figure 14.7.

    Figure 14.7. After making the cookie, the value of the document.cookie property is displayed.


  11. When the user clicks this button, the onClick event is triggered, and the user will be welcomed by the name he entered in the text box. See Figure 14.8.

    Figure 14.8. Retrieve the cookie and welcome the user!!


14.2.4 Retrieving Cookies from a Server

When retrieving cookies, you can only get those that were written for the server you are on and written by you. You cannot read and write cookies that belong to someone else or reside on a different server. In the last example, we got one cookie; in the following example all the cookies for this page are displayed.

Example 14.3
 <html><head><title>See my Cookies</title>     </head> 1   <body background="cookebg.jpg" onLoad="document.form1.reset()" >     <center>     <h2> Got milk?</h2> 2   <form name="form1">         Click to see document.cookie property         <p> 3       <input type="button" value="See Cookie" onClick="seeCookie();">         <p>     </form>     <script language="JavaScript"> 4  function seeCookie(){  5           if(document.cookie == ""){                document.write("No cookies");             }             else{ 6  var myCookie = document.cookie.split("; ");  7              for(var i=0;i<myCookie.length; i++){                   document.write("<body bgcolor=darkblue>                                   <font face=verdana color=white>");               //  document.write("<b>Cookie: " +                                  myCookie[i].split("=")[0] +"<br>"); 8                 document.write("<b>Cookie: " +  myCookie[i]  +                                  "<br>");                 }             }         }     </script>     </center>     </body>     </html> 


  1. After the document is loaded, the onLoad event is triggered and the values in the form are cleared with the reset() method.

  2. This is the start of an HTML form, called form1 .

  3. When the user clicks the button, the onClick event is triggered, and the seeCookie() function will be called to display all the cookies for this page.

  4. A function called seeCookie() is defined.

  5. First, we check to see if there are any cookies at all. If not, the alert box will say so.

  6. The split function splits up the cookie string by semicolons and returns an array called myCookie .

  7. The for loop iterates through each element of the myCookie array until the end of the array, myCookie.length , is reached.

  8. The value of the cookie is displayed. See Figure 14.9.

    Figure 14.9. IE cookies.


14.2.5 Deleting a Cookie

If you want to delete a cookie for the current page, set the expiration date of the cookie to a date earlier than the current date. This will cause the cookie to be deleted when the session ends.

Example 14.4
 <html><head><title>Delete Cookie</title><head>     <script name = "JavaScript">      var i = 0; 1  function delCookie (cookieName)  { 2  document.cookie = cookieName + "=" +"; expires=Thu, 01-Jan-1970   00:00:01 GMT";  alert("Cookie was deleted!");         seeCookie();     } 3   function seeCookie(){         if(document.cookie == ""){             alert("No cookies");             return false;         }         else{ 4  var myCookie = document.cookie.split("; ");  if ( i < myCookie.length ){ 5  document.form1.cookietype.value =   myCookie[i].split("=")[0];  i++;  //  Increase the index value to see the next cookie  }             else{alert("No more cookies");}         }     }     </script>     </head> 6  <body background="cookebg.jpg" onLoad="seeCookie()" >  <center>     <h2> Got milk?</h2> 7   <form name="form1"> 8       Is this the cookie you want to delete?         <br>         <input type="text" name="cookietype" >         <p> 9       <input type="radio"             name="radio"             value="choice" 9  onClick="delCookie(document.form1.cookietype.value);">Yes  <input type="radio"             name="radio"             value="choice" 10  onClick="seeCookie();">No  <p>     </form>     </center>     </body>     </html> 


  1. The function called delCookie() will remove a requested cookie. The name of the cookie, cookieName , is passed as a parameter to the function.

  2. The expiration date of the cookie is set to the beginning of UNIX time, also called epoch time ”January 1, 1970. Certainly this date has passed and the cookie will be deleted. After the cookie has been deleted, the seeCookie() function will be called, and the user will be presented with another cookie. If he clicks on the Yes radio button, that cookie will be removed.

  3. The function called SeeCookie() will check to see if there are any cookies remaining in the document.cookie property. If not, the program is over. To actually see if the cookies were deleted, close this session, and then reopen it.

  4. By splitting up the document.cookie property by semicolons, an array is created consisting of a name and value attribute of the cookie.

  5. The first element of the array, the name of the cookie, is assigned to the text box represented as document.form1.cookietype.value . It will appear in the text box for the user to see. Each time the function is called, the next cookie will be assigned to the text box, giving the user the option to delete that cookie.

  6. When the document has finished loading, the onLoad event is triggered, and calls the seeCookie() function. The first cookie name will appear in the text box.

  7. The HTML form starts here.

  8. The text box input type will be used to hold the cookie name.

  9. This radio button, when clicked, will called the delCookie() function. The user wants to remove this cookie. See Figure 14.10.

    Figure 14.10. The cookie's name is name . If the user clicks Yes (top), the cookie will be removed (bottom).


  10. This radio button, when clicked, means the user doesn't want to delete this cookie but would like to see the next cookie. When the user clicks No, the seeCookie() function will be called. After all the cookies have been shown, the alert message will say " No more cookies ".

Using the Browser to Remove Cookies

Another way to delete cookies is to go in your browser to the Tools menu in Navigator, then to the Cookie Manager, and then to Manage Stored Cookies. In IE, go to the Tools menu and Internet Options. See Figure 14.11. Then you can remove all or some cookies from the hard drive.

Figure 14.11. Netscape Navigator 7 Cookie Manager from the Tools menu (left); Internet Explorer from the Tools menu (right).


14.2.6 Cookie Help

Whether you like them, or hate them, you have complete control over whether to accept all cookies, some cookies, delete cookies, and so on. Check your particular browser for all of your options. For example, under the Help option in Navigator and IE, some of the cookie topics you might review are shown in Figure 14.12.

Figure 14.12. Cookie Help!


JavaScript by Example
JavaScript by Example (2nd Edition)
ISBN: 0137054890
EAN: 2147483647
Year: 2003
Pages: 150
Authors: Ellie Quigley

Similar book on Amazon

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