Controlling Cookies and Local Storage - Advanced JavaScript - JavaScript, 20 Lessons to Successful Web Development (2015)

JavaScript, 20 Lessons to Successful Web Development (2015)

PART II Advanced JavaScript

LESSON 17 Controlling Cookies and Local Storage

image

To view the accompanying video for this lesson, please visit mhprofessional.com/nixonjavascript/.

Your journey to become a master JavaScript programmer is progressing well, and you will now be able to write a wide variety of programs, but there are still quite a few more things you need to know before you become fully proficient in the language.

For example, web developers need a way to keep track of users to their websites, and historically this has generally been achieved through the use of cookies. Therefore, in this lesson I show you how to manage cookies from JavaScript, and I also introduce the newer and more powerful HTML5 feature called local storage.

Using Cookies

Cookies (the nonedible kind) are those little snippets of data that get saved on your computer and that everyone makes such a fuss about because some companies use them to track your surfing and buying habits. However, cookies are extremely useful and, in fact, invaluable for making your users’ visits to your web pages as smooth and enjoyable as possible.

You see, cookies are used by sites like Facebook and Twitter to keep you logged in so that you can keep going back without having to continually reenter your username and login details. And now I will show you how easy it is for you to set and read cookies using JavaScript, so that you can provide the same functionality.

To create a cookie, you simply assign it a value that contains the various details it needs to store on the user’s computer. These include the cookie name, its contents, its expiry date, the domain to which it applies, the path to the server issuing it, and whether it is secure or not. This may sound complicated, but look at the following (which I have split over two lines to avoid word wrapping at unexpected characters):

image

The cookie set by this assignment has the name username and the value fredsmith, and it will stay on the user’s computer (unless manually removed) until midnight on New Year’s Eve 2018 UTC (Universal Coordinated Time)—which is practically the same as GMT (Greenwich Mean Time), the time in London, England (without summer time, or daylight saving time).

However, it’s actually a little more complicated than that because to be able to store values in cookies such as special characters and spaces, they need to be run through the JavaScript encodeURI() function, which turns the unusual characters into escape sequences. Plus, I haven’t yet shown you how to set a cookie’s path, domain, and security.

Setting a Cookie

Therefore, let me provide you with a function you can use that will do all of these for you, including converting special characters to escape sequences:

image

If you use this function whenever you must set a cookie, all you need to think about is the arguments to pass to it, which are as follows:

name The cookie’s name.

value The cookie’s value.

seconds (Optional) The number of seconds until cookie expiry.

path (Optional) The path to the issuing server.

domain (Optional) The web domain to use.

secure (Optional) If ″secure″, the browser must use SSL.

The name and value arguments are quite clear, and now setting the optional expiry date is easier because you simply specify the number of seconds in the future before it should expire. Therefore, for example, for a month’s time, it would be 60 seconds × 60 minutes × 24 hours × 30 days, which gives a value of 2592000 seconds, so just supply that number as the argument value for seconds.

Regarding the optional path argument, this should generally either be left as ′′, not supplied, or you should choose a value of / so that the cookie will be accessible across all directories on the server. However, if you really need to restrict it to a certain subdirectory, such as /login/, then specify that instead.

The same goes for the optional domain argument. Generally, you can leave this as ′′ or not supply it and the cookie will work on the entire domain of the website (such as mysite.com). Or if you need to, you can specify a subdomain of your website such as subdomain.mysite.com to restrict access to the cookie to that domain only.

Finally, if you have a secure web server running and wish to restrict cookie exchanges to use the Secure Socket Layer (SSL) protocol, usually via HTTPS (HyperText Transfer Protocol Secure), then set the optional secure argument to true; otherwise (as is usually the case), don’t pass the argument, or set it to false.

Therefore, to make a call to only set a cookie’s value and expiry (leaving all other settings at their default values), you might issue a simple statement such as this:

SetCookie(’username’, ′fredsmith′, 2592000)

Reading a Cookie

Reading back a cookie’s value can also be a little tricky because all the cookies are stored in the single document.cookie string, so here’s another function you can use to extract individual cookies from the string:

image

This function first places a ; character before the document.cookie property and places the result in dc. This is because all cookies must end with a semicolon (which therefore must mark the start of the next one), and so searching for the start of a cookie is easily achieved by looking for;cookiename. However, the first cookie will not have a ; in front of it, so we prepend one to allow all instances to be searched.

The function then searches for the value in name (but prepended with a ; character, and followed by =) to see whether a cookie of that value exists, and returns false if not.

If a cookie name is matched, the cookie’s value is then read by extracting the string immediately following the = character up to the next ; character, which contains the value part of the key=value string. Any escape sequences are returned to special characters, and the result is returned. To read back a cookie you have saved on a user’s computer, you can use a statement such as this:

username = GetCookie(′username′)

The variable username will now either have the value false if the cookie was not found or it will contain the cookie’s value.

Deleting a Cookie

To delete a cookie, I have provided one further function you can call to also save you from having to write your own (even though it’s actually quite straightforward) as follows:

image

This function simply saves a cookie of the name in name with no value, and sets its expiry to –3600 seconds (1 hour in the past), whose result is that the cookie expires. To delete a cookie, therefore, you use a statement such as this:

DeleteCookie(′username′)

These three functions are saved for you in the file cookiefunctions.js in the accompanying archive so that you can include them in your code as required. Figure 17-1 shows them being tested in the accompanying file cookies.htm (also from the companion archive), with an alert window displaying the current value of a cookie.

image

FIGURE 17-1 Setting and reading a cookie

Once you’ve set a cookie for a user, the next time he or she returns to your website, just check for the existence of that cookie, and if it has a value, you can use it to look up their details and personalize your content for them. You can store passwords and other values in cookies too, and the reasonable 4-K size limit per domain of the document .cookie string means you can probably store all the cookies you could want.

image

If other people will have access to a user’s computer, they could possibly discover a password saved in a cookie by examining their cookies in the browser or an external cookie file, so it is preferable to use some kind of identifier that is not their password but that can identify the user to your web server and that you then immediately change to another value after reading it so that such values cannot be reused, as they are only ever temporary. Also, saving and reading cookies may not always work on a local file system on all browsers. If you intend to test these functions to be sure they will work, you may need to try them out on a web server using an http:// address, not a file:// address.

Using Local Storage

If you need to store much larger amounts of data than is possible with cookies, you can try saving them in the user’s HTML5 local storage space, which supports at least 2.5MB and up to 10MB per domain, depending on the browser.

To access local storage, you use methods of the localStorage object such as setItem(), getItem(), removeItem(), and clear(). For example, to locally store a user’s username and password, you might use code such as this:

image

If the size of the value is larger than the disk quota remaining for the storage area, an ″Out of memory″ exception is thrown. Otherwise, when another page loads or when the user returns to the website, these details can be retrieved to save the user entering them again, like this:

image

If the key doesn’t exist, the getItem() function returns a value of null. You don’t have to use these function names if you don’t want to, and can access the localStorage object directly, because the two following statements are equivalent to each other:

image

And the two following statements are therefore also equivalent to each other:

image

Figure 17-2 shows an alert() message window displaying these values being retrieved from local storage, using the following code:

image

image

FIGURE 17-2 Values have been retrieved from local storage.

The first part of code within the if() statement writes an error message to the web page if local storage is not supported in the browser. This is determined by examining the localStorage object and, if it is undefined, local storage is unavailable. In the else part of the code, a message is first written to the web page indicating that local storage is supported. Then the username and password are saved to local storage with the setItem() function.

Next, these values are retrieved from local storage into the variables username and password. Finally, an alert() message window is popped up that displays the retrieved values.

Until they are erased, these values will remain in the local storage once saved, and you can verify this by trying the preceding code for yourself (saved as localstorage.htm in the companion archive), running it once, commenting out the two lines of code that call setItem(), and then running it again—the alert window will still report the same vales.

Removing and Clearing Local Data

To remove an item of data from the local storage, all you need to do is issue a command such as this:

localStorage.removeItem(′username′)

This deletes the item from local storage. You can also completely clear the local storage for the current domain by issuing this command:

localStorage.clear()

image

Try any of these methods on the preceding example and run it again, and you’ll find that the values have been erased.

Summary

Using the information you have learned in this lesson, you will now be able to provide personalization to your websites to make your users feel right at home. If, for example, the site requires a username and password to participate, once these details have been entered one time, you can store them in cookies and automatically keep the person logged in until they choose to log out.

You now also have the ability to save large amounts of data in a user’s local storage space. How you use it is up to you, but you could, for example, support creating and storing memos, to-do lists, and other information locally, making it possible to create web apps that can be run offline without requiring access to a web server for storing data.

In Lesson 18 we’ll look at how you can further accommodate your users by tailoring their browsing experience to their particular browser.

Self-Test Questions

Using these questions, test how much you have learned in this lesson. If you don’t know an answer, go back and reread the relevant section until your knowledge is complete. You can find the answers in Appendix A.

1. Which DOM property holds cookie values?

2. How can you create a new cookie?

3. How can you read a cookie’s value?

4. How can you delete a cookie?

5. What is the purpose of the domain argument for cookie storage?

6. How can you test whether a browser supports local storage?

7. How can you save an item of data to local storage?

8. How can you read an item of data from local storage?

9. How can you remove an item of data from local storage?

10. How can you empty all local storage for the current domain?