1 / 59

Storing Information: Cookies

Learn how to store and retrieve user information using cookies on a website. Personalize the user experience and make suggestions based on their browsing patterns. Explore the cookie property in JavaScript and view stored cookies on Internet Explorer.

grahamh
Download Presentation

Storing Information: Cookies

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Storing Information: Cookies

  2. Our goal as website programmers should be to make the website experience as easy and pleasant for the user as possible. Clearly, well-designed pages with easily navigable layout are central to this, but they’re not the whole story. We can go one step further by learning about our users and using information gained about them to personalize the website. • For example, imagine a user, whose name we asked on the first visit, returns to our website. We could welcome the user back to the website by greeting him or her by name. Another good example is given by a website, such as Amazon’s, which incorporates the one-click purchasing system. By already knowing the user’s purchasing details, such as credit card number and delivery address, we can allow the user to go from viewing a book to buying it in just one click, making the likelihood of the user purchasing it that much greater. Also, based on information, such as the previous purchases and browsing patterns of the user, it’s possible to make book suggestions to the user.

  3. Such personalization on websites requires that information about users be stored somewhere in between their visits to the website. We’ve previously talked about the fact that accessing the user’s local file system from a web application is pretty much off limits due to security restrictions included in browsers. However, we, as website developers, can store small amounts of information in a special place on the user’s local disc, using what is called a cookie. There may be a logical reason why they are named cookies, but it also provides authors with the opportunity to make a lot of second-rate, food-related jokes!

  4. Baking Our First Cookie • The key to cookies is the document object’s cookie property. Using this property we can create and retrieve cookie data from within our JavaScript code. • We can set a cookie by setting document cookie to a cookie string. We’ll be looking in detail at how this cookie string is made up later in the chapter, but let’s first create a simple example of a cookie and see where the information is stored on the user’s computer.

  5. A Fresh Baked Cookie • The following code will set a cookie with the userName set as Paul, and an expiration date of 28 December 2010. • Save this as FreshBakedcookie.htm.

  6. Viewing Cookies on IE • Before we view the cookies, we’ll first clear the temporary internet file folder for the browser because this will make it easier to view the cookies that our browser has stored. In IF, select internet Options from the Tools menu, as shown in bellow.

  7. Click the Delete Files button under Temporary Internet files. We’ll be asked to confirm our request in another dialog box, shown in bellow.

  8. Check the Delete all offline content check box and then click OK. We’ll be returned to the internet Options dialog box. • Let’s have a look at the cookies we have currently residing on our machines. From the internet Options dialog box, click the Settings button next to the Delete button grouped under Temporary Internet files. We should see the dialog box shown in bellow.

  9. Now click the View Files button, and a list of all the temporary pages and cookie files on your computer will be displayed. if you followed the instructions previously and deleted all temporary internet files, all you should see are the cookie files on your computer, as these are not deleted. The number of cookie files on your computer will vary

  10. The actual cookies, their names, and their values, will look slightly different depending on your computer’s operating system. • We can delete each cookie simply by clicking it once, then pressing the Delete key, as you would with any file in Explorer. if we want to delete all cookies, IE 6 has a button on the general tab of the internet Options dialog box to delete cookies. • We can examine the contents of the cookies by double-clicking them

  11. As we can see, a cookie is just a plain old text file. Each website, or domain name, has its own text file where all the cookies for that website are stored. in this case there’s just one cookie currently stored for google.CO.uk. • Domains like amazon .Com will almost certainly have many cookies set. we can see the cookie’s details. Here, the name of the cookie is PREF; the domain google.CO.uk, and it relates to the root directory /. The contents probably look like a mess of characters.

  12. Now let’s load the FreahBakedCookie.htm page into our IE browser This will set a cookie. Let’s see how it has changed things by returning to the internet Options dialog box (by choosing the internet Options from the Tools menu). Click the Settings button, and then click View Files. My computer now shows the information shown in bellow.

  13. Because we are creating a cookie from a web page that is stored on the local hard drive rather than a server, its domain name has been set to code, the directory my page was stored in. Obviously, this is a little artificial. in reality people will be loading our web pages from our website on the internet and not off our local hard drive. The internet address is based on the directory the FreshBakedcookie.htm file was in. We can also see that it expires on December 28, 2010, as we specified when we created the cookie. Double-click the cookie to view its contents. • We can see the name we gave to the cookie at the left, userName, its value, Paul, and also the directory it’s applicable to. The expiration date is there as well; it’s just not in an easily recognizable form. Note that we may sometimes need to close the browser and reopen it before we see the cookie file.

  14. The Cookie String • When creating a cookie there are six parts we can set: name, value, expires, path, domain, and security, although the latter four of these are optional. We’ll now look at each of these in turn.

  15. name and value • The first part of the cookie string consists of the name and value for the cookie. The name is used so that we can reference the cookie at a later date, and the value is the information part of the cookie. • This name/value part of the cookie string is compulsory; it sort of defeats the point of the cookie if you don’t store a name or value because storing information is what cookies are all about. You should make sure that this part comes first in the cookie string. • The value for the cookie is a primitive string, although of course the string can hold number characters if it is numerical data that we want to store. if we are storing text, certain characters, such as semi-colons, cannot be used inside the value, unless we use a special encoding, which we’ll see later. in the case of semicolons, this is because they are used to separate the different parts of the cookie within the cookie string.

  16. In the following line of code, we set a cookie with the name userName and the value Paul. • This cookie has a very limited lifespan. By lifespan, we mean the length of time the information will continue to exist. if we don’t set an expiration date, a cookie will expire when the user closes the browser. The next time the user opens the browser the cookie will be gone. This is fine if we just want to store information for the life of a user session, which is a single visit by the user to our website. However, if we want to ensure that our cookie is available for longer, we must set its expiration date, which we’ll look at next.

  17. expires • If we want a cookie to exist for longer than just a single user session, we need to set an expiration date using the second part of the cookie string, expires, as follows: • The cookie set by the previous line of code will remain available for future use right up until December 28, 2010. Note that the format of the expiration date is very important, especially for IE browsers. it should be the same format it is given by the toGMTstring () method. This method is similar to the toUTCstring () method that we saw in Chapter 9.

  18. In practice, we’ll probably use the Date object to get the current date, and then set a cookie to expire three or six months after this date. Otherwise, we’re going to need to rewrite our pages on December 28,2010.For example, we could write the following: • This will create a new cookie called UserName with the value of Paul and it will expire 6 months from the current date. Note that other factors can cause a cookie to expire before its expiration date, such as the user deleting the cookie or the upper cookie limit being reached.

  19. path • We’ll find that 99 percent of the time, we will only need to set the name, value and expires parts of a cookie. However, at times the other three parts, such as the path part that we are looking at here, need to be set. The final two parts, domain and secure, are for more advanced use beyond the scope of a beginners’ book, but we’ll look at them briefly just for completeness. • We know that cookies are specific to a certain path, but what if we want to view our cookies from two different paths on our server? Say for example we have an online store at • www.mywebsite.com/ mystore/ but we subdivide the store into subdirectories, such as /Books and /Games. Now let’s imagine that our checkout is in the directory www.mywebsite.com/mystore/Checkout. Any cookies set in the /Books and /Games directories won’t be visible to each other or pages in the /Checknut directory. To get around this we can either set cookies only in the /mystore directory, since these can be read by that directory and any of its subdirectories, or we can use the path part of the cookie string to specify that the path of the cookie is /mystore even if it’s being set in the /Games or /Books or /Checkout subdirectories.

  20. For example, we could do this like so: • Now, the cookie will be available to all directories on the domain it is set from. if the website is just one of many at that domain, it’s best not to do this because everyone else will also have access to our cookie information. • It’s important to note that while Windows computers don’t have case-sensitive directory names, many other operating systems do. For example, if our website is on a Unix- or Linux-based server, the path property will be case sensitive.

  21. domain • The fourth part of the cookie string is the domain. An example of a domain is wrox.com or pawilton.com. Like the path part of the cookie string, the domain part is optional and it’s unlikely that you’ll find yourself using it very often. • By default, cookies are available only to pages in the domain they were set in. For example, if we have our first website running on a server with the domain MyPersonalwebSite.MyDomain.com and we have a second website running under MyBusinesswebsite . MyDomain.com, a cookie set in one website will not be available to pages accessed using the other domain name, and vice versa. • Most of the time this is exactly what we want, but if it is not, we can use the domain part of the cookie string to specify that a cookie is available to all subdomains of the specified domain.

  22. For example, the following sets a cookie that can be shared across both subdomains: • document.cookie =“UserName=Paul;expires=Tue, 28 Dec 2010 00:00:00;path-/” + ;domain-Myflomain.com;”; • Note that the domain must be the same: We can’t share www. SomeoneElsesDomain.com with www.MyDomain.com.

  23. secure • The final part of the cookie string is the secure part. This is simply a Boolean value; if it’s set to true the cookie will only be sent to a web sever that tries to retrieve it using a secure channel. The default value, which is false, means the cookie will always be sent, regardless of the security. This is only applicable where we have set up a server with SSL (Secure Sockets Layer).

  24. Creating a Cookie • To make life easier for ourselves, we’ll write a function that allows us to create a new cookie and set certain of its attributes with more ease. We’ll look at the code first and create an example using it shortly.

  25. The secure and domain parts of the cookie string are unlikely to be needed, so we just allow the name, value, expires, and path parts of a cookie to be set by the function. if we don’t want to set a path or expiration date, we just pass empty strings for those parameters. if no path is specified, the current directory and its subdirectories will be the path. if no expiration date is set, we just assume a date six months from now. • The first line of the function introduces the escape () function, which we’ve not seen before.

  26. When we talked about setting the value of a cookie, we mentioned that certain characters cannot be used directly, such as a semicolon. (This also applies to the name of the cookie.) To get around this problem, we can use the built-in escape() and unescape() functions. The escape () function converts characters that are not text or numbers into the hexadecimal equivalent of their character in the Latin-1 character set, preceded by a % character.

  27. For example, a space has the hexadecimal value of 20, and the semicolon has the value of 3B. So, the following code produces the output shown in Figure 1143. • alert(escape(”2001 a space odyssey;’)); • We can see that the spaces have been converted to %2 0, % indicating that they represent an escape or special character rather than an actual character, and that 20 is the ASCII value of the actual character The semicolon has been converted to %3B, as we’d expect.

  28. As we’ll see later, when retrieving cookie values we can use the unescape () function to convert from the encoded version to plain text. • Back to our function; we next have an if statement.

  29. This deals with the situation where an empty string, “, has been passed for the cookieExpires parameter of the function. Because most of the time we want a cookie to last longer than the session it’s created in, we set a default value for expires that is six months after the current date. • Next, if a value other than an empty string (“ “) has been passed to the function for the cookiepath parameter, we need to add that value when we create the cookie. We simply put path=” in front of any value that has been passed in the cookiepath parameter • Finally on the last line we actually create the cookie, putting together the cookieName, cookieValue, cookieExpires, and cookie Path parts of the string.

  30. We’ll be using the setcookie () function whenever we want to create a new cookie because it makes setting a cookie slightly easier than having to remember all the parts we want to set. More importantly, it can be used to set the expiration date to a date six months ahead of the current date. • We’ll now put this together in a simple example in which we use our setcookie () function to set three cookies named Name, Age, and FirstVisit. We then display what is in the document. cookie property to see how this has been affected.

  31. Save the example as createcookie.htm, and then load it into a web browser • Note that all three cookies are displayed as name/value pairs separated by semicolons, and also that the expiration date is not displayed. if we had set the path parameter, this also would not have been displayed. The UserName cookie from a previous example is also displayed.

  32. Getting a Cookie’s Value • In the preceding example, we used document.cookie to retrieve a string containing information about the cookies that have been set. However, this string has two limitations. • First, the cookies are retrieved in name/value pairs, with each individual cookie separated by a semicolon. The expires, path, domain, and secure parts of the cookie are not available to us and cannot be retrieved. • Second, the cookie property allows you to retrieve only all the cookies set for a particular path and, when hosted on a web server, that web server So, for example, there’s no simple way of just getting the value of a cookie with the name Age. To do this we’ll have to use the string manipulation techniques we’ve learned in previous chapters to cut the information we want out of the returned string. • A lot of different ways exist to get the value of an individual cookie, but the way we’ll use has the advantage of working with all cookie-enabled browsers. We use the following function:

  33. Getting a Cookie’s Value • In the preceding example, we used document.cookie to retrieve a string containing information about the cookies that have been set. However, this string has two limitations. • First, the cookies are retrieved in name/value pairs, with each individual cookie separated by a semicolon. The expires, path, domain, and secure parts of the cookie are not available to us and cannot be retrieved. • Second, the cookie property allows you to retrieve only all the cookies set for a particular path and, when hosted on a web server, that web server So, for example, there’s no simple way of just getting the value of a cookie with the name Age. To do this we’ll have to use the string manipulation techniques we’ve learned in previous chapters to cut the information we want out of the returned string.

  34. A lot of different ways exist to get the value of an individual cookie, but the way we’ll use has the advantage of working with all cookie-enabled browsers. We use the following function:

  35. The first task of the function is to get the document cookie string and store it in the variable cookieValue. • Next we need to find out where the cookie with the name passed as a parameter to the function is within the cookievalue string. We use the indexof 0 method of the String object to find this information, as shown in the following line. • The method will either return the character position where the individual cookie is found or -l if no such name, and therefore no such cookie, exists. We search on + cookieName + “=“ so that we don’t inadvertently find cookie names or values containing the name that we require. For example, if we have xFoo, Foo, and yFoo as cookie names, a search for Foo without a space in front would match the xFoo first, which is not what we want!

  36. If cookieStartsAt is -1, the cookie does not exist or it’s at the very beginning of the cookie string so there is no space in front of the cookie name. To see which of these is true, we do another search, this time with no space. • in the next if statement we check to see whether the cookie has been found. if it hasn’t, we set the cookieValue variable to null.

  37. If the cookie has been found, we get the value of the cookie we want from the document . cookie string in an else statement. We do this by finding the start and the end of the value part of that cookie. The start will be immediately after the equals sign following the name. So in the following line, we find the equals sign following the name of the cookie in the string by starting the indexof () search for an equals sign from the character at which the cookie name/value pair starts. • We then add one to this value to move past the equals sign. The end of the cookie value will either be at the next semicolon or at the end of the string, whichever comes first. We do a search for a semicolon, starting from the cookiestartsAt index in the next line.

  38. If the cookie we are after is the last one in the string, there will be no semicolon and the cookieEndsAt variable will be -1 for no match. in this case we know the end of the cookie value must be the end of the string, so we set the variable cookieEndsAt to the length of the string. • We then get the cookie’s value using the substring () method to cut the value that we want out of the main string. Because we have encoded the string with the escape () function, we need to unescape it to get the real value, hence the use of the unescape () function.

  39. Finally we return the value of the cookie to the calling function. • Now we know how to create and retrieve cookies. Let’s use this knowledge in an example where we check to see if any changes have been made to a website since the user last visited it. • We’ll be creating two pages for this example. The first is the main page for a website; the second is the page with details of new additions and changes to the website. A link to the second page will only appear on the first page if the user has visited the page before (that is, a cookie exists) but has not visited since the page was last updated.

  40. This page needs to be saved as MainPage.htm. Note that it contains the two functions, setCookie () and getcookievalue ( ), that we created earlier. Also note that the image whatsNew. gif is referenced by this page; either create such an image, or retrieve the image from the code download. • Next, we’ll just create a simple page to link to for the What’s New details. • Save this page as WhatsNew.htm.

  41. Load MainPage.htm into a browser. The first time we go to the main page, there will be just a heading saying “Welcome to my website”. Obviously if this were a real website, it would have a bit more than that, but it suffices for our example. However, refresh the page and suddenly we’ll see the page shown bellow. • If we click on the image, we’re taken to the whatsNew.htm page detailing all the things added to the website since we last visited.

  42. How It Works • The whatsNew.htm page is just a simple html page with no script, so we will confine our attention to MainPage.htm. in the head of the page in the first script block, we declare the variable lastupdated. • Whenever we make a change to the website this variable needs to be changed. it’s currently set to Tue, 28 Dec 2010 just to make sure we see a “What’s New” image when we refresh the page. A better alternative for live pages would be the document.lastModified property, which returns the date the page was last changed. • The rest of the first script block contains the two functions getcookievalue () and setcookie () that we looked at earlier These haven’t changed, so we won’t discuss them in detail here.

  43. The interesting material is in the second script block that is found within the body of the page. First we get the date of the user’s last visit stored in the LastVisit cookie using the getcookievalue () function. • if it’s null, the user has never been here before, or it has been six or more months since the last visit, and the cookie has expired. Either way, we won’t put a “What’s New” image up because everything is new if the user is a first time visitor, or a lot has probably changed in the last six months—more than what our What’s New page will detail. • if lastvisit is not null, we need to check whether the user visited the site before the site was last updated, and if so direct the user to a page that shows what is new. We do this within the if statement.

More Related