Modern Web Architecture: The HTML5 Web Storage

April 12, 2012 in HTML5, JavaScript, Web 2.0

Abstract

One of the most important features of HTML5 is the Web Storage feature. Using the Web Storage feature, the client state can be saved on the browser level without consuming the network bandwidth or the server memory. The Web Storage increases the scalability of the web applications on the server level and on the network level. In this article, I will show you how to work with the HTML5 Web Storage feature.

Difference between the old cookies and the HTML5 Web Storage

Unlike cookies, the HTML5 Web Storage is more scalable. The HTML5 Web Storage content is not transferred between the client and the server per every request. This means using the HTML5 Web Storage, you can store unlimited amount of information on the browser without affecting the network bandwidth. While the web cookies have a limited size, and are transferred between the server and the client per every request.

Checking if the browser is supporting the HTML5 Web Storage

HTML5 Web Storage is supported in most of the modern browsers (IE8, Firefox, Safari, Chrome, and Opera). To check if the Web Storage is supported, check if the web storage objects are defined as follows.

function isStorageSupported() {
	if (typeof(localStorage) === "undefined" || typeof(sessionStorage) === "undefined") {
		alert("Web Storage is no suppored ...");
		return false;
	}
	
	return true;
}

The HTML5 Web Storage Objects

The Web Storage is represented by two main objects the localStorage object and the sessionStorage object. The main difference between them is that the localStorage object is stored in the browser with no expiration date, however, the sessionStorage object is stored in the browser and is removed once the user session ends (i.e., its life time is the user session). It is important to know that there is another difference which is localStorage can work in local mode while the sessionStorage can work only inside a hosted page on the server.

If you try to run the sessionStorage in local mode, you will face an error. For example, the error message in Firefox is:

Operation is not supported

I created an example that illustrates how to use the HTML5 Web Storage objects. In this example, there is a text area “information” field and four buttons for (saving the “information” field value in localStorage, retrieving the stored “information” field value from localStorage, saving the “information” field value in sessionStorage, retrieving the stored “information” field value from sessionStorage).

To store any data in the localStorage object, just add the information in the (key, value) form as follows:

localStorage.key = value;

In the example to store the “information” field data in the localStorage object:

localStorage.information = document.getElementById("information").value;

To retrieve the data from the localStorage object, you can retrieve it using the key as follows:

alert(localStorage.key);

In the example to get the “information” data from the localStorage object:

alert("Data from local storage is: " + localStorage.information);
document.getElementById("information").value = localStorage.information;

Using the sessionStorage object is pretty the same as localStorage. In the example to store the “information” field data in the sessionStorage object:

sessionStorage.information = document.getElementById("information").value;

To get the “information” data from the sessionStorage object:

alert("Data from session storage is: " + sessionStorage.information);
document.getElementById("information").value = sessionStorage.information;

I attach below, the complete example code:

<!DOCTYPE html>
<HTML>
<HEAD>
	<TITLE>Welcome to the WebStorage test</TITLE>
	
	<SCRIPT type="text/javascript">
	
		function isStorageSupported() {
			if (typeof(localStorage) === "undefined" || typeof(sessionStorage) === "undefined") {
				alert("Web Storage is no suppored ...");
				return false;
			}
			
			return true;
		}
	
		function storeInformationInLocalStorage() {
			if (isStorageSupported()) {
				localStorage.information = document.getElementById("information").value;
			}
		}
		
		function readInformationFromLocalStorage() {
			if (isStorageSupported()) {
				alert("Data from local storage is: " + localStorage.information);
				document.getElementById("information").value = localStorage.information;
			}			
		}		
	
		function storeInformationInSessionStorage() {
			if (isStorageSupported()) {
				sessionStorage.information = document.getElementById("information").value;
			}
		}
		
		function readInformationFromSessionStorage() {
			if (isStorageSupported()) {
				alert("Data from session storage is: " + sessionStorage.information);
				document.getElementById("information").value = sessionStorage.information;
			}				
		}	
	
	</SCRIPT>
</HEAD>
<BODY>
	<label for="information">Enter some information in the textArea: </label><br/>
	<textarea id="information" rows="2" cols="20"></textarea>	
	<br/><br/>

	<INPUT TYPE="button" value="Store in the localStorage" onclick="javascript:storeInformationInLocalStorage()"/>
	<INPUT TYPE="button" value="Read from the localStorage" onclick="javascript:readInformationFromLocalStorage()"/>

	<br/>

	<INPUT TYPE="button" value="Store in the sessionStorage" onclick="javascript:storeInformationInSessionStorage()"/>
	<INPUT TYPE="button" value="Read from the sessionStorage" onclick="javascript:readInformationFromSessionStorage()"/>	
</BODY>
</HTML>

You can delete any of the key/value pairs in the Web Storage using the sessionStorage.removeItem(key) and the localStorage.removeItem(key). If you want to delete all of the key/value pairs, you can use the sessionStorage.clear() and localStorage.clear().

I attach the example for your reference here.

20 comments on “Modern Web Architecture: The HTML5 Web Storage

  1. :) Another relevant and nicely composed article! Keep up the good work my friend!

  2. Pingback: HTML5 | Pearltrees

  3. There are obvious advantages, but what are the cons? Security is the big issue here. How secure is the local storage? Given the perverse brilliance of hackers, I can see this being an issue.

    Thoughts?

  4. Yes Bill, definitely security is one of the today’s issues in the web storage because of XSS attacks. However, I don’t see it is major in the case of session storage because the data is cleaned up once the user session ends.

    So my recommendation is not to store sensitive client data in the local storage because there is a way to enumerate the keys. If there is a necessary need to store this data in local storage, it should be encrypted. The server (not the client) must do this sort of encryption and decryption i.e., the key must not be stored in the local storage.

    • Jason on said:

      so, would that mean localStorage can be overwritten by others? Lets say a goes to my page, I put something in localStorage with the key “bob” and the value “bob is a user”. They leave my page and go somewhere else and some other page puts in localStorage something with a key of “bob” but with a different value. The user then goes back to my page and tries to retrieve “bob” what value is given?

      • If you navigate to another domain then you will have a new Storage. Because every Storage is associated with a domain.

        What I meant in my previous comment is that hacker can inject domain-based malicious JavaScript code through site comments ,for example, to get this information so it is recommended to close this door from the beginning in the face of the hacker.

  5. Nicely composed. Decent explanation.
    Excellent one.!!!

  6. shmuel on said:

    Interesting article. Keep doing good works

  7. Great concise article on HTML 5. Keep ‘em coming.

  8. chilly on said:

    nice article thx. good balance of depth and clarity. very useful and timely for me. also I didn’t know IE8 supported local storage which makes it more viable for my work. cheers.

  9. Jason on said:

    Another question: what is the size limit per key value? How many keys are supported? Lets say I am a malicious hacker. A user comes to my page. My javascript starts executing and tries something like this pseudocode?

    for(i=0;i<100000;i++)
    {
    for(w=0;w<100000;w++)
    {
    localStorage.temp+i+w = i;
    }
    }
    Sure, it is a contrived example, but the point is, can a malicious js like this crash out a browser by eating memory? Or are the browsers good enough to catch this kind of stuff?

  10. Enrique on said:

    Thanks for the post. Good and easy to follow.

    Just one note. Don’t do this:

    if (isStorageSupported()) {
    sessionStorage.information = document.getElementById(“information”).value;
    }

    do that:

    if (!isStorageSupported()) { /* throw exception */ }
    sessionStorage.information = document.getElementById(“information”).value;

    Conditional code must “brace” exception conditions, not normal flow. Otherwise your code will be more complex than needed because is not the same to write:
    if (condException1) { /* throw exception */ }
    if (condException2) { /* throw exception */ }
    if (condException3) { /* throw exception */ }
    “normal_code_flow”

    than this:
    if (!condException1) {
    if (!condException2) {
    if (!condException3) {
    “normal_code_flow”
    }
    }
    }

  11. confused on said:

    I’m confused… The title indicates HTML 5, but the code written for the storage (either local or session) is in javascript and the HTML 5 code is interacting with the script. So how is local or session storage an HTML 5 feature if javascript is required to handle the actual function of storing and reading the data?

    • HTML5 Storage is an API specification. Once a browser natively implements the API, you generally “speak” to it via Javascript, which is the lingua franca of browser engines.

      • Confused on said:

        Wouldn’t that make it a Javascript API though since it has to be “spoken” to in javascript? Isn’t that just giving HTML 5 the ability to utilize a javascript resource?

        • Just because Javascript is prevalent today doesn’t mean it is the only option. As inconceivable as it might sound, another language in the future could be the dominant choice… like Dart for example.

          HTML is a standard, and an enduring one. Ergo, if Chrome decided to have a heart of Dart, you’d still be able to call the HTML5 Web Storage “API” in a standardized manner if the spec was being respected. Atleast, that’s the idea.

  12. Pingback: Links for April 16th through April 21st — Vinny Carpenter's blog

Leave a reply

Your email address will not be published. Required fields are marked *

320,911 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by sweet Captcha