Thursday, 9 May 2013

HTML5 WebStorage


Why WebStorage?

Your application data can be stored locally, doesn’t that look great? Whenever user refreshes web page, do you really like to see requests made from his browser to download all the data from server over and over again ? If you are working on a user interactive application and want to implement pause/resume feature, will you really want the application state to be saved in the server even though the client does not want to switch his  browser? Traditional ways of implementing state management, data caching, storage of user preference and many more are going to get changed with the introduction of WebStorage.
There are basically two kinds of WebStorage; LocalStorage and SessionStorage

What is LocalStorage?

Its a part of web storage API. It permits web browsers to store data in the form of Key-Value pair. You can store and retrieve your application data without leaving the burden to  server. And the data will still be available even after a browser refresh, navigate to a different web page, browser tab close or browser window close!

What is SessionStorage?

Its almost like LocalStorage. You can store your data in SessionStorage in the form of Key-Value pair. But the difference is that here the data is not persisted across tabs and browser windows. But you can still refresh the page and get the data.

Browser support

Currently WebStorage is supported in following browsers
IEFirefoxSafariChromeOperaIPhoneAndroid
8+3.5+4.0+4.0+10.5+2.0+2.0+

Lets start…

Before getting into details of LocalStorage, to set the context, lets get familiar with an HTML5 attribute called ‘contenteditable’. If you set this attribute value to true, the component will allow to change its content. Below given an example.
<html>
 <head>
 <script>
 </script>
 </head>
 <body>
 <p id='note' style="border-style:solid;height:300px;width:300px" contenteditable="true">
 Enter your notes here
 </p>
 </body>
</html>
Try typing inside that box. Yeah! its cool right? Just another HTML5 feature. Can you try refreshing the page? Your changes are gone! Think about a ‘sticky note’ app, which allows users to enter some quick notes which will be saved automatically. Can we use  ’contenteditable’ attribute in that scenario. Yes. You can very well do that. But the problem is ‘How to save the notes’? The answer is to apply LocalStorage.
Include the script given below into your page.
window.onload = function() {
 var note = document.getElementById('note');
 note.onblur = storeData; 
 if(localStorage.getItem('data')){
 note.innerHTML = localStorage.getItem('data');
 }
}
function storeData(){
 localStorage.setItem('data',this.innerHTML);
}
You can see the previously entered data even after page refresh, close tab and close browser window.

Any other ways to access data? 

Yes. You can also use simple square brackets ['key']  or dot annotation (.) to access the data. There are also methods available to remove an item and clear all items. You can also find out the length of the total values in the LocalStorage using ‘length’ and get keys based on index using ‘key(index)’
<html>
 <script>
 window.onload = function() {
 var note = document.getElementById('note');
 var point = document.getElementById('point');

 note.onblur = storeNotes; 
 point.onblur = storePoints; 
 if(localStorage['notes']){
 note.innerHTML = localStorage['notes'];
 }
 if(localStorage.points){
 point.innerHTML = localStorage.points;
 }
 }
 function storeNotes(){
 localStorage['notes'] = this.innerHTML;
 }
 function storePoints(){
 localStorage.points = this.innerHTML;
 }
 function removeNotes(){
 localStorage.removeItem('notes');
 }
 function removePoints(){
 localStorage.removeItem('points');
 }
 function clearAll(){
 localStorage.clear();
 }
 </script>
 <body>
 <p id='note' style="border:red solid 1px;height:300px;width:300px;float:left" contenteditable="true">
 Enter your notes here
 </p>
 <button onclick='removeNotes()'>Remove Notes</button>
 <div id='point' style="border:blue solid 1px;height:300px;width:300px;float:right" contenteditable="true">
 Enter your points here
 </div>
 <button onclick='removePoints()' style='float:right'>Remove Points</button>
 <br>
 <button onclick='clearAll()' style='left:250px;position:relative'>Remove All</button>

 </body>
</html>

Still not looking great?

Okay. How do you feel if you get a handle whenever the locally stored data is modified?  You can attach eventListener to LocalStorage object. Please note that storage events don’t work for same window or tab. Events are fired only for other window or tab that use same localStorage. If you open the page in two different tabs or browsers, you can see the event fired.
<html>
 <script>
 window.onload = function() {
 if (window.addEventListener) {
 window.addEventListener("storage", updateHistory, false);
 } else {
 window.attachEvent("storage", updateHistory);
 };

 var note = document.getElementById('note');

 note.onblur = storeNotes; 
 if(localStorage['notes']){
 note.innerHTML = localStorage['notes'];
 }
 }
 function storeNotes(){
 localStorage.setItem('notes',this.innerHTML);
 }
 function updateHistory(event) {
 if (!event) { 
 event = window.event; 
 }
 if(event.key==='notes') {
 var hist = document.getElementById('history');
 localStorage['history'] = localStorage['history'] +'<br>Note modified <b>old Value</b> : '+event.oldValue+'<b> new Value</b> : '+event.newValue+ '<b> url</b> : '+event.url;
 hist.innerHTML = localStorage['history'];
 }
 }
 </script>
 <body>
 <p id='note' style="border:red solid 1px;height:200px;width:300px;" contenteditable="true">
 Enter your notes here
 </p>
 <br>
 <h2>History of notes</h2>
 <div id='history' style="border:blue solid 1px;height:200px;width:300px;overflow-y: scroll;">

 </div> 
 </body>
</html>

 Be careful!

WebStorage is supported only in the browsers which I have listed above. It is always better to put a condition at the beginning before you leverage its functionalities.
if('localStorage' in window) {
 /*Use localStorage only if its supported*/
 }
 if('sessionStorage' in window) {
 /*Use localStorage only if its supported*/
 }
Most of the browsers which support WebStorage has an arbitrary limit of five megabytes per origin. So you may have to opt for a different mechanism if more data has to be stored, which I plan to cover in my next blog.

No comments:

Post a Comment