Photo of Professor Lawley

Professor
Lawley

Website Design
& Implementation

IGME-230 / Fall 2018

JS Exercise 6: Web Storage API
(Week 10, Tuesday 10/30)

HTML pages are generally “stateless”–even if you change elements on the page based on user interaction, reloading the page sets it back to its original state.

You can save state information about a page (and a site) by storing data on the user’s computer using one of two methods: “cookies” or the Web Storage API. Cookies are name/value pairs typically used for things like session management, personalization, and user tracking. The Web Storage API introduced with HTML5 also allows us to use JavaScript to store key:value data in the user’s browser, and retrieve that information when the user returns to the site. This API allows more data storage than cookies, and is more secure.

For this exercise, you'll be using the files in the webstorage.zip file. You should download and unzip that folder now.

Web Storage Resources

Before you begin, review these two pages on the MDN site:

Tips for Troubleshooting Your Code

Slow Down! Be sure to work through the code slowly, making sure that you understand each line and what it's doing. If you only copy and paste, you'll have a hard time when/if you have to use the commands in any way other than exactly what's here.

Choose Meaningful Variable Names!It should be easy to tell from your variable names what they're being used for. The more specific, the better. The variable "foodsList", for instance, could be an array, or an ordered list, or an unordered list. In contrast, "numberedFoodsList" or "orderedFoodsList" would probably be an <ol> element.

Comment every line! If you add comments after every line of code, saying in your own words what that line is doing, it will be much easier to both understand and debug your code.

Test Early And Often! Test each step before moving on to the next one. Testing doesn't just mean loading the page. It also means looking at the console so that you can identify any errors.

A Web Storage Example

Open the webstorage-1.html file in a browser. Change the name in the text box, and choose a different value from the select menu. Then close the window, and re-open the file. Your changes should be preserved. That's because each time you change the value of the textbox or the selected drop-down item, their values are written to localStorage.

Open the Developer Tools pane, and select the Storage tab in Firefox, or the Application tab in Chrome. Find the current host for your page in the local storage section (if you opened the file directly, it will be file://; if you're using a live preview, it will be something like http://127.0.0.1 ). You should see the two key/value pairs listed.

Now open the file in an editor. If you've reviewed the MDN pages above, you should be able to get a sense of what's happening.

One thing that's not immediately obvious is why we're adding a prefix to our variables.

Web Storage links keys to the server name/domain on which they're created. That means that if you use it on a shared server like people.rit.edu, two people who use the same key name in their application could overwrite each other's data. One way around this on a shared server is to prefix your key names with something unique, like your username.

On GitHub Pages, this is less of a problem because the server name already includes your username. However, if you were to set up two different JavaScript applications, and they both used the same key (like "name", for instance, or "highscore"), they could end up interfering with each other. In that case, you'd want to add a prefix that was specific to the application.

Storing Objects with Web Storage

A major limitation of Web Storage is that it doesn't allow us to store arrays or other objects directly. Happily, there's an easy workaround:

You can easily convert built-in JavaScript objects (Object, Array, Date, etc) to and from a string representation, and then save the string to localStorage. This is known as serialization.

Data that has been serialized in this way uses a structure known as JSON, or JavaScript Object Notation. MDN has an excellent page explaining how to work with JSON files, which you can use as reference: Working with JSON.

Below are examples of how you could store an array as a string, and then retrieve it from storage and place it back into an array.

Save An Array to localStorage with JSON.stringify()

Retrieve an Array from localStorage with JSON.parse()

Important Notes About Web Storage

Storage Limits

The process by which the browser works out how much space to allocate to web data storage and what to delete when that limit is reached is not simple, and differs between browsers. You can find more information on the MDN Browser storage limits and eviction criteria page.

"Blocking" Behavior

Because localStorage is a synchronous (blocking) API, it's important to know that DOM updates to your page will "hang" whenever localStorage is being updated by your code. What this means is that you should be careful about when you update your localStorage values.

In a game for example, it wouldn't be wise to update your highScore localStorage value inside of your game loop, since it could be running 60 times a second. Doing so would seriously harm the game's performance. Instead, do the localStorage update only occasionally, for instance when a level or the entire game are completed. You can read more about this in Nolan Lawson's post "IndexedDB, WebSQL, LocalStorage – what blocks the DOM?".

Deliverable

Open the webstorage-exercise.html file in an editor. It's a copy of the webstorage-1.html file, with one minor change: Since this is going onto your GitHub Pages site, which has a unique domain name, there's no need for your user name in the prefix. However, "name" is a pretty common variable, one which you might want to use in another exercise or project. So I've changed the prefix to wsExercise- so that the stored value will be unique to this exercise.

All you need to do now is modify the code so that the user's color choice will also change the background color for the page. (Conveniently, the value for each of the choices is a CSS color keyword...)

The color change effect should happen when the user changes the color using the select menu, and should persist when the user reloads the page.

Don't overthink it. This can be done with only two lines of code!

When you're done, link the file to your landing page with the name JS Web Storage Exercise, and upload it no later than the start of class on Thursday, 11/1.