HTML5 Recipes: More on Storage

In this recipe, we shall cover some more material on HTML5 localStorage and how you can store JSON objects and retrieve them.

The examples that we shall see in this recipe will enable you to think in terms of complex data that you can cache / save locally in your browser based web applications. There are various reasons to cache data locally. The most important reason is to avoid the network call across the server for data that is not likely to change. Another key reason is to give a better user experience in terms of being able to remember where the user was, the last time that they used the application. Implementing such behavior in your web applications, makes them more useful, powerful and much closer in functionality, that is expected from non-browser based applications.

We are going to see two code snippets, both the code snippets show how you can store and retrieve back JSON objects using the local Storage API.

Let us take a look at the code below:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HTML Storage Test</title>
<script type="text/javascript">

function saveLocal(){
	if (window.localStorage) {
		var scores = [];
		scores.push("Romin,10 seconds");
		scores.push("Neil,20 seconds");
		scores.push("Aryan,30 seconds");
		localStorage.setItem("highscores",JSON.stringify(scores));
		alert("The data has been stored successfully.");
	} else {
		alert("Your Browser does not support LocalStorage.");
	}
}

function readLocal(){
	if (window.localStorage) {
		//get the highscores object
		var scores = localStorage.getItem("highscores");
		scores = JSON.parse(scores);
		for (i=0;i<scores.length;i++){
			alert(scores[i]);
		}
	}
}

</script>
</head>
<body>
<div id="main">
	<input type="button" value="Save Values" onclick="saveLocal()"/>
	<input type="button" value="Read Values" onclick="readLocal()"/>
</div>
</body>
</html>

Let us break the code down now:

  • We have two buttons, “Save Values” and “Read Values”. When you click the “Save Values” button, we invoke the saveLocal() method.
  • The saveLocal() method first checks if your browser supports local storage. Then it creates a Javascript array, where each element in the array is of type string.
  • Finally, we save it using the setItem() method of the local Storage API. Note that we are using the JSON.stringify method to get the string representation of this array. The setItem() methods takes two parameters: the key value “highscores” under which the data i.e. the Array of Strings is stored.
  • When you click the “Read Values” button, we use the getItem() method of the local Storage API. The parameter passed to this method is the key value i.e. “highscore”.
  • This will return back a string value, which is then decoded back into the array of strings via the JSON.parse method. We then simply print out the values for reference

Note that at any time, you should use your browser developer tools to view the data that has been stored. For e.g. in Google Chrome, go to Settings –> Tools –> Developer Tools and look under the section named LocalStorage for the key-values that you have stored. Since we have used the localStorage and not sessionStorage, these values will be persisted across browser restarts too.

See it in action here.

Let us take a look at another piece of code below:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HTML Storage Test</title>
<script type="text/javascript">

function saveLocal(){
	if (window.localStorage) {
		var person = {"firstname":"Romin","lastname":"Irani","age":36};
		var highscores = [{"name":"Romin Irani","time":"25s"},{"name":"Dave Mathews","time":"30s"},{"name":"Rich Tretola","time":"35s"}]
		localStorage.setItem("highscores",JSON.stringify(highscores));
		localStorage.setItem("person",JSON.stringify(person));
		alert("The data has been stored successfully.");
	} else {
		alert("Your Browser does not support LocalStorage.");
	}
}

function readLocal(){
	if (window.localStorage) {
		//Get the person object
		var person = localStorage.getItem("person");
		person = JSON.parse(person);
		alert(person.firstname + " " + person.lastname + " is " + person.age + " years old.");

		//Get the highscores object
		var scores = localStorage.getItem("highscores");
		scores = JSON.parse(scores);
		for (i=0;i<scores.length;i++){
			alert(scores[i].name + " finished in " + scores[i].time);
		}
	}
}
</script>
</head>
<body>
<div id="main">
	<input type="button" value="Save Values" onclick="saveLocal()"/>
	<input type="button" value="Read Values" onclick="readLocal()"/>
</div>
</body>
</html>

Let us break the code down now:

  • The above example is similar to the previous one, where we save and read back values.
  • This code shows a JSON Object and another one i.e. an array of JSON objects that are persisted into localStorage and then read back. If you were writing some web based game, you can imagine storing all the moves that a player makes, so that you can replay them back at any point in time.

See it in action here.


HTML5 Storage Recipes

  1. Getting Started with Storage
  2. More on Storage

Back to HTML5 Series

 

 

Advertisements

One thought on “HTML5 Recipes: More on Storage

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s