HTML and CSS Reference
In-Depth Information
Arrays in LocalStorage
Arrays can be stored in the same way that objects are. First you must convert the array to JSON, and then you can
store it as a string. To retrieve your array, you just need to parse the JSON that has been stored. The following ex-
ample code shows how you could store and retrieve arrays using LocalStorage:
// Create an array.
var myArray = [“Mike", “Jim", “Becky", “Jo", “Steph"];
// Convert the array to JSON.
var myJsonArray = JSON.stringify(myArray);
// Store the JSON.
localStorage.setItem(“myArray", myJsonArray);
. . . . and to retrieve the array:
// Retrieve the JSON.
var retrievedJson = localStorage.getItem(“myArray");
// Parse the JSON.
var myNewArray = JSON.parse(retrievedJson);
Using JSON allows you to maintain your data structures when using a simple datastore such as LocalStorage. You
should consider, however, whether you are using this facility correctly. LocalStorage is designed only to hold simple
data. If you want to store multiple objects that have the same structure, you are better off using a database.
HTML5 does introduce a way of maintaining a client-side database through the IndexedDB API, which isn't
covered in this topic. If you're interested, I encourage you to look into it. You can find a great tutorial on how to use
IndexedDB on HTML5Rocks at http://www.html5rocks.com/en/tutorials/indexeddb/todo/ .
SessionStorage
As I mention earlier in this chapter, LocalStorage is persistent. The data you save stays there when you close your
browser. This is exactly what you want for most applications; but there may be instances when you want to tempor-
arily store some data, such as session IDs (what applications use to identify different users). It can be a pain to re-
member to remove all this from LocalStorage when the user leaves your page and ends the session.
SessionStorage was developed to solve this problem. This API has the exact same functions as LocalStorage (under
the hood, it uses the same basic Storage object), but the data you save in SessionStorage is wiped by the browser
when the user closes the window and ends his or her session on your website.
To use SessionStorage, you simply call your functions on the sessionStorage object instead of localStor-
age , as shown in the following examples:
sessionStorage.setItem(“name", “Joe Balochio");
sessionStorage.getItem(“name");
sessionStorage.key(0);
sessionStorage.removeItem(“name");
Search WWH ::




Custom Search