HTML5 Web Storage advantages over Cookies

This post will make you well introduced with the new term, i.e. HTML5 web storage. Here in this post you will have a complete concept of HTML5 web storage, either its introduction, its advantage over cookies, where to use it and how to use it, browser support for web storage and so on and so forth. Actually Web Storage is a new HTML5 API which offers numerous benefits over traditional cookies.

“HTML5 Storage” is a specification named Web Storage, which was at one time part of the proper HTML5specification but later it was split out into its own specification. It is also referred as “Local Storage” or “DOM Storage”. Let’s start with a brief introduction to HTML5 web storage.

Introduction to HTML5 web storage

Let us first understand what is HTML5 Storage? Simply it is a way or method for web pages to store named key/value pairs locally, within the client web browser. Similar to cookies, you may persist data even after you navigate away from the web site, or close your browser tab, or exit your browser, or whatever. But in contrast to cookies, these data is never transmitted to the remote web server unless and until you send it manually. It is implemented natively in web browsers, and hence it is available even when third-party browsers plug-in are not.

In order to understand web storage in better manner, we should also take a look over cookies so that we can understand that what are those things due to which cookies has been replaced by web storage.

Cookies-Current HTTP state storage

The most popular method for local storage in all browsers is in HTTP cookies. Nowadays there are countless websites (for example Google, Facebook, Amazon, New York Times) which relies on HTTP cookie to store various kinds of data such as user preference, login information, shopping cart and so on. If you want to see it practically, then disable cookie in your browser and try to access extremely popular web applications like Facebook, Twitter, Gmail, and Amazon and so on, you will probably see screenshots as below:

GoogleNoCookie

FacebookCookie

AmazonNoCookie

So, one thing is clear that, in order to use these web giants cookie enabled is a mandatory condition. Now, you must be thinking, when major web application like Facebook, Google and Amazon are using cookies, then what are the drawbacks of cookies that it is getting replaced by web storage. Let us see why it is so?

Limitations of Cookies

In earlier days, also used these days somewhere, we were having with cookies which used to prove as a huge driving factor for the Web. But it still has certain limitation. There would be no doubt to say that Cookies affected the way of web world both in good and bad way. Some of its limitations are enlisted below which has been overcome by HTML5 web storage:

1) Cookies allow us to login automatically to sites we use frequently, such as Gmail and Facebook. At the same time with cookies, our search and browsing history can be tracked and our privacy is a concern.

2) Data-capacity limitations are another problem with cookies. The data storage limit of cookies in many web browsers is about 4 KB per cookie. Although many browsers allow 30 to 50 cookies, so if anybody wants to exceed the 4 KB limit of one cookie he/she could create another one, it is still a limitation if there is a need of enormous storage.

3) Due to storage capacity problem, developers usually store user and/or session identifiers in cookies, and for rest of the data they use server-side databases.

4) In addition to these, one of the major side effects of cookies is that they are always sent with every HTTP request even for images which results in huge traffic of data being sent over the wire leading sometimes the blockage of the data.

Whatever be the limitations of cookies, it has been overcome by the HTML5 web storage and usually preferred by the web developers, designers or programmers while developing any web applications. It is said that where cookies left off, Web Storage picks up. So, let’s move forward with HTML5 web storage.

Moving Forward with Web Storage

It is well known that web storage has lots of advantages over cookies and play a vital role in any web application. Generally, least but not last, the strength of Web Storage is seen in three things.

1) First, it is easy to use for web developers; it has a simple API to get and set key/value pairs.

2) Secondly, it provides the huge amount of data storage space which; the default disk space quota offer no less than 5 or 10 MB to be stored per domain. This means one can store much more besides just basic user/session info on the client-side. It also allows you for user preference settings, localization data, and temporary offline storage for batching server writes and much more.

3) Thirdly, the data being stored in the web storage can be accessed using JavaScript which gives you the ability to leverage client-side scripting to do many things.

Web Storage Objects: Session Storage and Local Storage

There are two types of Web Storage objects:-
1) SessionStorage
2) LlocalStorage

SessionStorage is designed to store data in a single web page session and is available only within the browser tab or window session.

LocalStorage is designed to be kept even between browser sessions which means data is still available even when the browser is closed and reopened, and also instantly between tabs and windows.

The basic difference between both of them is that sessionStorage is window or tab isolated while localStorage is shared across pages under a domain. In other words, we can say that sessionStorage takes care of storing temporary data during an HTTP session life time happened in one browser window/tab, each window/tab can maintain its own session data; While localStorage stores data persists into user’s hard disk, and all pages under this concrete domain can manipulate the localStorage.

In both cases, Web Storage data is not available between different browsers. For example, storage objects created in Firefox cannot be accessed in Google Chrome, exactly similar to cookies.

Database Storage

Till now, we have been limited to key-value pairs. But there may be certain situations when you might be dealing with a larger volume of web data; in that situation, database storage is the right option for you. With HTML5 web storage solution, you get database storage, which allows you to save structed data in the client’s machine using a real SQL database. Browsers that have implemented this feature use SQLite database which is light and fast. Since, database storage is currently the least implemented and supported client storage method, hence you will rarely see it in use or mentioned in any blogs, articles or tutorials.

Let’s see demo of both LocalStorage as well as SessionStorage one by one, in which we have added a Counter which will store natural number into sessionStorage, and a clickable button will increase the Counter. Look at the code snippet given below:

Let’s open two instances of the page, respectively click Counter++ on each page, then we will see each of them keeps its own counter:

SessionStorage-Demo

In contrast to SessionStorage data stored in localStorage could be accessed by all pages under the same domain, in the demo shown below. Initially we have inserted a fake UserProfile into localStorage, and then opened another page which has different path but lie under the same domain; now, we will see UserProfile stored by first page can be retrieved.

LocalStorage-Demo

Here it should be noted that localStorage is shared, and it is therefore, it might be manipulated by more than one page simultaneously. It is due to this reason that, W3 emphasized that the browser should implement Storage mutex to ensure the Thread safe of localStorage.

Due to these mechanisms, sessionStorage / localStorage are supposed to replace cookie with a more straight-forward, effective and secure manner.

Where to Use Web Storage

Web Storage can be a great or winning performance where there is a need of access static data to be stored on the client side. It works well where some static data is stored on the client in order to minimize the number of subsequent requests; one can store even images in strings using Base64 encoding. Implementation of web storage can also be seen where there is a need for storing the data for an online to-do list and then pushing it to the server in intervals instead of in real-time or saving products that the user places in his shopping cart.

Also, in some cases, sometimes a need is felt to use any application offline. This can be easily done using LocalStorage object. In this case, data can then be sent and stored server-side when the user is online again. The data can be made available between page requests, multiple browser tabs, and also between browser sessions using LocalStorage; this is where the web storage becomes handy to use.

One question might be arising in your mind that, in the above cases, one can use LocalStorage, then where one should use SessionStorage. SessionStorage can be effectively used at the place where you want to get rid of the data as soon as the window is closed, or you don’t want the application to interfere with the same application that’s open in another window. In the scenario where you need to run two instances of the same application opened in different tab of the same browser, SessionStorage serves at its best.

Web Storage Event

W3 defines StorageEvent interface as below:

Interface StorageEvent: Event

{
Readonly attribute DOMString key;
Readonly attribute any oldValue;
Readonly attribute any newValue;
Readonly attribute DOMString URL;
Readonly attribute Storage storageArea;
Void initStorageEvent(in DOMString typeArg, in boolean canBubbleArg,
in boolean cancelableArg, in DOMString keyArg, in any oldValueArg,
in any newValueArg, in DOMString urlArg, in Storage storageAreaArg);
};

Browser Support for Web Storage

Web Storage is well supported by every modern browser starting from IE8, Firefox 3.5, Safari 4, Google Chrome 4, and Opera 10.50. Let’s see HTML web storage support for different browsers as listed below:

Html5 Storage Support

IE-8.0+
FIREFOX-3.5+
SAFARI-4.0+
CHROME-4.0+
OPERA-10.5+
IPHONE-2.0+
ANDROID-2.0+

Check for HTML5 Storage

One can access HTML5 Storage through the localStorage object on the global window object from JavaScript code. Before using HTML5 web storage one should check whether the browser supports it or not through the following code:

Function supports_html5_storage()
{
try
{
return ‘localStorage’ in window && window[‘localStorage’] !== null;
}
catch (e)
{
return false;
}
}

If you are not interested in writing the above lines of function code by yourself, you may use Modernizr to detect support for HTML5 Storage.

If (Modernizr.localstorage)
{
// window.localStorage is available!
}
else
{
// no native support for HTML5 storage :
(
// maybe try dojox.storage or a third-party solution
}

If the browser does support, then invoking sessionStorage and localStorage in JavaScript is fairly easy. The below given sample code demonstrates how to set, get, remove or clear items to or from the storage:

// Set/Get locallStorage
localStorage.{key} = strValue;
var localVal = localStorage.{key};

// Set/Get sessionlStorage
sessionStorage.{key} = strValue;
var sessionVal = sessionStorage.{key};

// Remove an storage item
localStorage.removeItem(‘key’)
sessionStorage.removeItem(‘key’)

// Clear storage
localStorage.clear();
sessionStorage.clear();

Using HTML5 Web Storage

You should know that HTML5 Storage is based on named key/value pairs and you need to store data based on a named key, and then retrieving that data with the same key. The named key is a string. Although, the data can be of any type supported by JavaScript, such as strings, Booleans, integers, or floats, however the data is actually stored as a string. If you are storing and retrieving anything other than strings, you need to use functions like parseInt() or parseFloat() to coerce your retrieved data into the expected JavaScript data type.

Interface Storage
{
Getter any getItem(in DOMString key);
Setter creator void setItem(in DOMString key, in any data);
};

Here in the above code, calling setItem() with a named key that already exists will silently overwrite the previous value and calling getItem() with a non-existent key will return null value rather than throwing an exception.

You can treat the localStorage object as an associative array just like other JavaScript objects. Instead of using the getItem() and setItem() methods, you can simply use square brackets. For example, go through the below given snippet of code:

Var foo = localStorage.getItem(“bar”);
// …
localStorage.setItem(“bar”, foo);
…could be rewritten to use square bracket syntax instead:
var foo = localStorage[“bar”];

// …
localStorage[“bar”] = foo;
Also, for removing the value for a given named key, and clearing the entire storage area or in other words you can say deleting all the keys and values at once, there are several methods. For Example:

Interface Storage
{
deleter void removeItem(in DOMString key);
Void clear();
};

Here, calling removeItem() method with a non-existent key will do nothing.

Finally, there is a property to get the total number of values in the storage area, and to iterate through all of the keys by index in order to get the name of each key.

Interface Storage
{
Readonly attribute unsigned long length;
Getter DOMString key(in unsigned long index);
};

Here, calling key() function with an index that is not between 0–(length-1), and hence, the function will return null.

Security Concerns

If you will take security concerns of using Web Storage, you should be aware of the fact that, using Web Storage is really not more secure in comparison to cookies. As it is universally known that, with greater power brings greater responsibility with it, in the same manner while using Web Storage, one should be very aware of its security aspects. It is advisable that neither store sensitive data like passwords and credit card numbers on the client-side, nor send this kind of data to the client.

However, SSL does a great deal of resolving security issues and means that the client and server must communicate only encrypted data. This is the reason why you see more and more websites using the more secure https protocol.

Conclusion:

Going through the above post, one thing must have become clear to you that Web Storage are just like cookies which store all the information like user preference, login information, etc locally and which can be turned on/off by the user. Locally stored information allows sites to authenticate, store site preferences, remember shopping cart contents, or identify a server-based session. HTML5 came up with a well structured, consolidate and standardize client side storage solution which is categorized into three approaches, i.e. LocalStorage, SessionStorage and Database storage. HTML5 web storage is designed to store name/value pairs on the web client. Overall, we can say that the entire mechanism of the HTML5 web storage is remarkable to such an extent that it has brought revolution in the web application development.

Jennifer Adam

The area of interest of Jennifer Adam is to cater technologically advanced and powerful tool which works remarkably with multiple browsers and devices. Being a talented professional of inkyROBO, she is capable of implementing the innovative ideas and also loves to write inspiration blogs.