JavaBlog.fr / Java.lu HTML5,WEB HTML5/WEB: localStorage, sessionStorage, Persistence UserData

HTML5/WEB: localStorage, sessionStorage, Persistence UserData

Hi,

In this post, I will try to present you the HTML5 localStorage and sessionStorage, their differences, examples to illustrate our writes, the browser compatibility and another technologies Persistence UserData.

Presentation: Advantage and difference
LocalStorage and SessionStorage are new HTML5 technologies that allow to save data in the client (web browser), unlike to sessions “normal” which save the data in the server.

These technologies allow to store large amounts of data without having to use cookies or constant dialogue with a remote database, such as Ajax. A database storage via Ajax creates a larger network traffic and can work in connected mode. So the great advantage of these new technologies is that they can access the data without going through the server, which improves the performance (and the speed).

More, they allow the storage of data from 5MB to 10MB and offering features Read/Modify/Delete. When the allocated space is reached, an alert should be triggered to ask the user if he agrees to increase the allocated space.

There are two types of web storage :

  • The localStorage:
    – They are stored in the browser (they persist after the closure of the browser or tab),
    – They “resist” to the clearing of cache,
  • The sessionStorage:
    – They are recorded at the tab (close the tab or the browser results in loss of information),
    – A same page opened in multiple tabs, will have several independent contexts,

The difference between LocalStorage and SessionStorage is the first backup data without taking account of a time limit. SessionStorage, by cons, backup data during a single session. So the data in a SessionStorage, will not be accessible in a new tab.

All elementary data types are supported (integer, string, decimal …) as String. These data are stored as an associative array (key = value). However, save an array or an object, it is necessary to pass through a stage of serialization like JSON. More, the BASE64 encoding can be done in order to store binary data.

Storage Interface
This interface provides the access to the sessionStorage and localStorage.
Below, the methods and properties of the Storage interface :

  • setItem (key, data): Store a data in the Storage component,
  • getItem (key): Get the data associated with a given key,
  • removeItem (key): Remove the data associated with a given key,
  • key (indexNumber): Get the the data stored in the ‘indexNumber’ position,
  • clear (): Remove all stored data,
  • length: Return the number of stored data,

Examples
The sessionStorage and localStorage technologies implement this Storage interface. In the each following example, we will create 2 pages: one page for the setting of data and another for the getting of data from storage. Then, we will check the behaviour of each technologies relative to the browser (opening, closure of tab or window).

Example 1: use of sessionStorage
As reminder, sessionStorage sets fields on the window. When the window is closed, the session fields are lost, even if the site remains open in another window.

  • Pages
    indexSetItem.html: set the data in Storage

    <html>
    	<head>
    		<META http-equiv="Cache-Control" content="no-cache"> 
    		<META http-equiv="Pragma" content="no-cache"> 
    		<META http-equiv="Expires" content="0"> 
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=8" />
            <title>HTML Page setup Tutorial</title>
    	</head>
     		<script type="text/javascript">
    		sessionStorage.setItem("MyKey" ,"MyValue");
    		sessionStorage.setItem("MyDate" ,new Date());
     		</script>
    
    	<body>
    		Data are set in Storage!!!
    		<br/> -> Click <a href="./indexGetItem.html">here</a> to access to the page of reading these items in Storage.
    	</body>
    </html>
    

    indexGetItem.html: get the data from Storage

    <html>
    	<head>
    		<META http-equiv="Cache-Control" content="no-cache"> 
    		<META http-equiv="Pragma" content="no-cache"> 
    		<META http-equiv="Expires" content="0"> 
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    		<meta http-equiv="X-UA-Compatible" content="IE=8" />
            <title>HTML Page setup Tutorial</title>
    	</head>
     		<script type="text/javascript">
     		
    		var keyValue = sessionStorage.getItem("MyKey");
    		var dateValue = sessionStorage.getItem("MyDate");
    		
    		alert("Session storage : MyDate = " + dateValue + " MyKey = " + keyValue );
     		
     		</script>
    
    	<body>
    		GetItems will be called in javascript alert!!!
    		<br/>Click <a href="./indexSetItem.html">here</a> to set again the items in Storage!
    		
    	</body>
    </html>
    
  • Tests
    • Open the URL http://localhost:8080/test_html5_1/sessionStorage/indexSetItem.html in order to set the items in Storage, then click on the link in opened page to get the items from Storage (http://localhost:8080/test_html5_1/sessionStorage/indexGetItem.html):
      => OK, no loss of data in the storage
    • Open the URL http://localhost:8080/test_html5_1/sessionStorage/indexSetItem.html in order to set the items in Storage, then close the browser and open a new browser with the URL http://localhost:8080/test_html5_1/sessionStorage/indexGetItem.html to get the items from Storage:
      => loss of data in the storage
    • Open the URL http://localhost:8080/test_html5_1/sessionStorage/indexSetItem.html in order to set the items in Storage, then close the tab (not the browser) and open a new tab with the URL http://localhost:8080/test_html5_1/sessionStorage/indexGetItem.html to get the items from Storage:
      => loss of data in the storage
    • Open the URL http://localhost:8080/test_html5_1/sessionStorage/indexSetItem.html in order to set the items in Storage, then open a new browser window WITHOUT New SESSION and go to the URL http://localhost:8080/test_html5_1/sessionStorage/indexGetItem.html to get the items from Storage:
      => loss of data in the storage
    • Open the URL http://localhost:8080/test_html5_1/sessionStorage/indexSetItem.html in order to set the items in Storage, then open a new browser window WITH New SESSION and go to the URL http://localhost:8080/test_html5_1/sessionStorage/indexGetItem.html to get the items from Storage:
      => loss of data in the storage

Example 2: use of localStorage
AS reminder, localStorage sets fields on the domain. Even when you close the browser, reopen it, and go back to the site, it remembers all fields in localStorage.

  • Pages
    indexSetItem.html: set the data in Storage

    <html>
    	<head>
    		<META http-equiv="Cache-Control" content="no-cache"> 
    		<META http-equiv="Pragma" content="no-cache"> 
    		<META http-equiv="Expires" content="0"> 
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=8" />
            <title>HTML Page setup Tutorial</title>
    	</head>
     		<script type="text/javascript">
     		
     		localStorage.setItem("MyKey" ,"MyValue");
     		localStorage.setItem("MyDate" ,new Date());
    		
     		</script>
    
    	<body>
    		Data are set in Storage!!!
    		<br/> -> Click <a href="./indexGetItem.html">here</a> to access to the page of reading these items in Storage.
    	</body>
    </html>
    

    indexGetItem.html: get the data from Storage

    <html>
    	<head>
    		<META http-equiv="Cache-Control" content="no-cache"> 
    		<META http-equiv="Pragma" content="no-cache"> 
    		<META http-equiv="Expires" content="0"> 
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=8" />
            <title>HTML Page setup Tutorial</title>
    	</head>
     		<script type="text/javascript">
     		
    		var keyValue = localStorage.getItem("MyKey");
    		var dateValue = localStorage.getItem("MyDate");
    		
    		alert("Local storage : MyDate = " + dateValue + " MyKey = " + keyValue );
     		</script>
    
    	<body>
    		GetItems will be called in javascript alert!!!
    		<br/>Click <a href="./indexSetItem.html">here</a> to set again the items in Storage!
    		
    	</body>
    </html>
    
  • Tests
    • Open the URL http://localhost:8080/test_html5_1/localStorage/indexSetItem.html in order to set the items in Storage, then click on the link in opened page to get the items from Storage (http://localhost:8080/test_html5_1/localStorage/indexGetItem.html):
      => OK, no loss of data in the storage
    • Open the URL http://localhost:8080/test_html5_1/localStorage/indexSetItem.html in order to set the items in Storage, then close the browser and open a new browser with the URL http://localhost:8080/test_html5_1/localStorage/indexGetItem.html to get the items from Storage:
      => OK, no loss of data in the storage
    • Open the URL http://localhost:8080/test_html5_1/localStorage/indexSetItem.html in order to set the items in Storage, then close the tab (not the browser) and open a new tab with the URL http://localhost:8080/test_html5_1/localStorage/indexGetItem.html to get the items from Storage:
      => OK, no loss of data in the storage
    • Open the URL http://localhost:8080/test_html5_1/localStorage/indexSetItem.html in order to set the items in Storage, then open a new browser window WITHOUT New SESSION and go to the URL http://localhost:8080/test_html5_1/localStorage/indexGetItem.html to get the items from Storage:
      => OK, no loss of data in the storage
    • Open the URL http://localhost:8080/test_html5_1/localStorage/indexSetItem.html in order to set the items in Storage, then open a new browser window WITH New SESSION and go to the URL http://localhost:8080/test_html5_1/localStorage/indexGetItem.html to get the items from Storage:
      => OK, no loss of data in the storage

Example 3: use of localStorage with JSON serialization
AS reminder, localStorage sets fields on the domain. Even when you close the browser, reopen it, and go back to the site, it remembers all fields in localStorage.

  • Pages
    indexSetItem.html: set complex data (array, object, array of complex objects) in Storage

    <html>
    	<head>
    		<META http-equiv="Cache-Control" content="no-cache"> 
    		<META http-equiv="Pragma" content="no-cache"> 
    		<META http-equiv="Expires" content="0"> 
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    		<meta http-equiv="X-UA-Compatible" content="IE=8" />
            <title>HTML Page setup Tutorial</title>
    	</head>
     		<script type="text/javascript">
    
    		// Store array with JSON serialization
    		var myTable = [ 'val1', 'val2', 'val3' ]; 
    		localStorage.setItem("myTableInJSON", JSON.stringify(myTable));
    
    		// Store complex object with JSON serialization
    		var myObject = { 
    			myKey1: 'myValue1',   
    			myKey2: 'myValue2' 
    		};  
    		localStorage.setItem("myObjectInJSON", JSON.stringify(myObject));
    
    		// Store array of complex objects with JSON serialization
    		var robots = [];
    		for(var i=0; i<10; i++){ 
    			var robot = {};
    		
    			robot.number = robots.length + 1;
    			robot.dateCreation = new Date();
    			robot.label = "Robot with the number " + robot.number;
    				
    			// Add robot in the list of robots 
    			robots[robots.length] = robot;
    		} // end-block
    		localStorage.setItem("robotsInJSON", JSON.stringify(robots));
     		</script>
    
    
    	<body>
    		Data are set in Storage!!!
    		<br/> -> Click <a href="./indexGetItem.html">here</a> to access to the page of reading these items in Storage.
    	</body>
    </html>
    

    indexGetItem.html: get complex data (array, object, array of complex objects) in Storage

    <html>
    	<head>
    		<META http-equiv="Cache-Control" content="no-cache"> 
    		<META http-equiv="Pragma" content="no-cache"> 
    		<META http-equiv="Expires" content="0"> 
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    		<meta http-equiv="X-UA-Compatible" content="IE=8" />
            <title>HTML Page setup Tutorial</title>
    	</head>
     		<script type="text/javascript">
     		// Get the array stored with JSON serialization
    		var myTable =  JSON.parse(localStorage.getItem("myTableInJSON"));
    		alert(myTable[0]); // val1
    		
    		// Get the complex object stored with JSON serialization
    		var myObject = JSON.parse(localStorage.getItem("myObjectInJSON"));
    		alert(myObject.myKey1 + ' - ' + myObject.myKey2);
    
    
    		// Get the array of complex objects stored with JSON serialization
    		var robots = JSON.parse(localStorage.getItem("robotsInJSON"));
    		for (i=0; i < robots.length; i++) {
    			alert(robots[i].number + ' - ' +  robots[i].dateCreation + ' - ' + robots[i].label);
    		} // end-for
    
     		</script>
    
    
    	<body>
    		GetItems will be called in javascript alert!!!
    		<br/>Click <a href="./indexSetItem.html">here</a> to set again the items in Storage!
    		
    	</body>
    </html>
    
  • Tests
    • Open the URL http://localhost:8080/test_html5_1/localStorageWithJson/indexSetItem.html in order to set the items in Storage, then click on the link in opened page to get the items from Storage (http://localhost:8080/test_html5_1/localStorageWithJson/indexGetItem.html):
      => OK, no loss of data in the storage and the complex data are correctly retrieved.

Compatibility
These technologies are not cross browser compatible, all browsers are compatible, except for Internet Explorer 6 and 7. So it is necessary to check if the user’s browser supports this technology. A typical error encountered is the javascript error ‘localStorage is null or not an object’. So, it is necessary to check the version of browser which must work at least in IE8 mode (these localStorage and sessionStorage will not work in IE7 mode).

This site http://www.quirksmode.org/dom/html5.html details the HTML5 compatibility for localStorage and sessionStorage components in all modern browsers.

More, to check if the user’s browser supports a technology, there is a good javascript library named Modernizr which offers the possibility to test whether technology HTML5 is supported by the browser like:

if (Modernizr.localstorage && Modernizr.sessionstorage) {
}else{
	// the technologie is not supported by the browser.
} 

Persistence UserData
This concept of “cookies capacity” is not new. Internet Explorer since version 5 supports a system named Persistence allows to specify which objects will persist during a browsing session. Persistence is something quite broad and includes within it several Behaviours like userData behavior, which can save large amounts of data using XML. This is the equivalent of the object sessionStorage DOM Storage.

Use of Persistence and especially the userData behavior is a little more complex than using DOM Storage. Persistence data is stored as an XML tree, and before trying to store and retrieve data, it is necessary to specify the “branch XML” (not the node) on which we are working.

The operating principle of userData is not identical to DOM Storage. With userData, we must specify an HTML element as part of “transit” with a CSS class. It is through this that the data element to store and retrieve channeled. In fact, this element will serve as an object, on which we will apply the methods and properties.

To define an element of transit, we use the CSS property behavior (non-property W3C):

<style type="text/css">
        .storeuserData { behavior: url(#default#userData); }
</style>

Thus, the element (or elements) with the class element acts storeuserData transit. For simplicity, it is recommended to use a form element with input=text or input=hidden.

Here a simple example of writing and getting of data:

// Create the object oPersist
var oPersist = document.getElementById("oPersistInput"); 
 
// Writing
oPersist.setAttribute("user", oPersist.value);
oPersist.save("oXMLBranch");
 
// Getting
oPersist.load("oXMLBranch");
alert(oPersist.getAttribute("user"));

The load and save methods have as argument the name of the branch to use XML. If the branch does not exist, it is clearly established. The setAttribute and getAttribute methods are exactly the same as those used to define an attribute and access it via the DOM. And in reality, it is logical, since the data is stored in a XML branch! This means that you can add multiple attributes to the same branch! The recorded data are stored as XML attributes and not as a key / value as is the case with DOM Storage.

Conclusion
Here is a small tutorial that has explained how to use SessionStorage and LocalStorage with JSON serialization. The alternatives to these technologies are cookies, the Flash technologies (FLEX…) and the Persistence userData.

Source: HTML5_Storage_WebContent.zip

Best regards,

Huseyin OZVEREN

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

Related Post