Chapter: Internet & World Wide Web HOW TO PROGRAM - The Ajax Client - JavaScript: Objects

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Using Cookies - JavaScript(Js)

Cookies provide web developers with a tool for personalizing web pages.

Using Cookies


Cookies provide web developers with a tool for personalizing web pages. A cookie is a piece of data that is stored on the user’s computer to maintain information about the client during and between browser sessions. A website may store a cookie on the client’s com-puter to record user preferences or other information that the website can retrieve during the client’s subsequent visits. For example, a website can retrieve the user’s name from a cookie and use it to display a personalized greeting.


Microsoft Internet Explorer and Mozilla Firefox store cookies as small text files on the client’s hard drive. When a user visits a website, the browser locates any cookies written by scripts on that site and makes them available to any scripts located on the site. Note that cookies may be accessed only by scripts belonging to the same website from which they originated (i.e., a cookie set by a script on can be read only by other scripts on


Cookies are accessible in JavaScript through the document object’s cookie property. JavaScript treats a cookie as a string of text. Any standard string function or method can manipulate a cookie. A cookie has the syntax identifier=value, where identifier is any valid JavaScript variable identifier, and value is the value of the cookie variable. When mul-tiple cookies exist for one website, identifier-value pairs are separated by semicolons in the document.cookie string.


Cookies differ from ordinary strings in that each cookie has an expiration date, after which the web browser deletes it. This date can be defined by setting the expires property in the cookie string. If a cookie’s expiration date is not set, then the cookie expires by default after the user closes the browser window. A cookie can be deleted immediately by setting the expires property to a date and time in the past.


The assignment operator does not overwrite the entire list of cookies, but appends a cookie to the end of it. Thus, if we set two cookies


document.cookie = "name1=value1;"; document.cookie = "name2=value2;";


document.cookie will contain "name1=value1; name2=value2".


Figure 11.15 uses a cookie to store the user’s name and displays a personalized greeting. This example improves upon the functionality in the dynamic welcome page example of Fig. 6.17 by requiring the user to enter a name only during the first visit to the web page. On each subsequent visit, the script can display the user name that is stored in the cookie.


Line 10 begins the script. Lines 12–13 declare the variables needed to obtain the time, and line 14 declares the variable that stores the name of the user. Lines 16–27 contain the same ifelse statement used in Fig. 6.17 to display a time-sensitive greeting.

Lines 30–66 contain the code used to manipulate the cookie. Line 30 determines whether a cookie exists on the client computer. The expression document.cookie evalu-ates to true if a cookie exists. If a cookie does not exist, then the script prompts the user to enter a name (line 45). The script creates a cookie containing the string "name=", fol-lowed by a copy of the user’s name produced by the built-in JavaScript function escape (line 49). The function escape converts any non-alphanumeric characters, such as spaces


      <?xml version = "1.0" encoding = "utf-8"?>


      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"




      <!-- Fig. 11.15: cookie.html -->


      <!-- Using cookies to store user identification data. -->


      <html xmlns = "">




      <title>Using Cookies</title>


        <script type = "text/javascript">



        var now = new Date(); // current date and time


        var hour = now.getHours(); // current hour (0-23)


        var name;

              if ( hour < 12 ) // determine whether it is morning


        document.write( "<h1>Good Morning, " );



hour = hour - 12; // convert from 24-hour clock to PM time


// determine whether it is afternoon or evening

if ( hour < 6 )

document.write( "<h1>Good Afternoon, " );


document.write( "<h1>Good Evening, " );

} // end else

        // determine whether there is a cookie


        if ( document.cookie )


// convert escape characters in the cookie string to their

// English notation

         var myCookie = unescape( document.cookie );


// split the cookie into tokens using = as delimiter

         var cookieTokens = myCookie.split( "=" );       


// set name to the part of the cookie that follows the = sign

        name = cookieTokens[ 1 ];


        } // end if



// if there was no cookie, ask the user to input a name

name = window.prompt( "Please enter your name", "Paul" );

//       escape special characters in the name string

//       and add name to the cookie

        document.cookie = "name=" + escape( name );


} // end else


        name + ", welcome to JavaScript programming!</h1>" );


document.writeln( "<a href = 'javascript:wrongPerson()'> " +

"Click here if you are not " + name + "</a>" );

        // reset the document's cookie if wrong person


        function wrongPerson()


//       reset the cookie

document.cookie= "name=null;" +  

         " expires=Thu, 01-Jan-95 00:00:01 GMT";


//       reload the page to get a new name after removing the cookie



        } // end function wrongPerson


        // -->








        <p>Click Refresh (or Reload) to run the script again</p>





Fig. 11.15 | Using cookies to store user identification data.

and semicolons, in a string to their equivalent hexadecimal escape sequences of the form “%XX,” where XX is the two-digit hexadecimal ASCII value of a special character. For example, if name contains the value "David Green", the statement escape( name ) evaluates to "David%20Green", because the hexadecimal ASCII value of a blank space is 20. It is a good idea to always escape cookie values before writing them to the client. This con-version prevents any special characters in the cookie from being misinterpreted as having a special meaning in the code, rather than being a character in a cookie value. For instance, a semicolon in a cookie value could be misinterpreted as a semicolon separating two adja-cent identifier-value pairs. Applying the function unescape to cookies when they are read out of the document.cookie string converts the hexadecimal escape sequences back to English characters for display in a web page.

If a cookie exists (i.e., the user has been to the page before), then the script parses the user name out of the cookie string and stores it in a local variable. Parsing generally refers to the act of splitting a string into smaller, more useful components. Line 34 uses the Java-Script function unescape to replace all the escape sequences in the cookie with their equiv-alent English-language characters. The script stores the unescaped cookie value in the variable myCookie (line 34) and uses the JavaScript function split (line 37), introduced in Section 11.4.5, to break the cookie into identifier and value tokens. At this point in the script, myCookie contains a string of the form "name=value". We call split on myCookie with = as the delimiter to obtain the cookieTokens array, with the first element equal to the name of the identifier and the second element equal to the value of the identifier. Line 40 assigns the value of the second element in the cookieTokens array (i.e., the actual value stored in the cookie) to the variable name. Lines 52–53 add the personalized greeting to the web page, using the user’s name stored in the cookie.

The script allows the user to reset the cookie, which is useful in case someone new is using the computer. Lines 54–55 create a hyperlink that, when clicked, calls the JavaScript function wrongPerson (lines 58–66). Lines 61–62 set the cookie name to null and the expires property to January 1, 1995 (though any date in the past will suffice). Internet Explorer detects that the expires property is set to a date in the past and deletes the cookie from the user’s computer. The next time this page loads, no cookie will be found. The reload method of the location object forces the page to refresh (line 65), and, unable to find an existing cookie, the script prompts the user to enter a new name.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Copyright © 2018-2020; All Rights Reserved. Developed by Therithal info, Chennai.