HTML5 Web Storage
Disadvantages of cookies
- The storage limit of cookies in web browsers is limited to about 4KB.
- Cookies are sent with every HTTP request, thereby slowing down the web application performance.
What is HTML5 web storage?
It is a simple client side database that allows the users to persist data in the form of key/value pairs. It has a fairly simple API to retrieve/write data into the local storage. It can store up to 10MB of data per domain. Unlike cookies, the data stored are not included with every HTTP request.
Types of web storage
Local storage: Stores data with no expiration date. The data will be available even when the browser/ browsing tab is closed or reopened.
Session storage: Stores data for one session. Data persisted will be cleared as soon as the user closes the browser.
The following snippet accesses the current domain's local Storage object and adds a data item to it using Storage.setItem().
if(window.localStorage)
{
localStorage.setItem('myCat', 'Tom');
}
Note: QUOTA_EXCEEDED_ERR exception will be thrown if the storage limit exceeds 5MB. So it is always better to add try/catch blocks to the storage code while saving data.
We can check whether the data is stored in local storage by using the developer tools that comes with the browsers. For instance, in Chrome, right click on the browser and select Inspect Element. Select Resources tab and then click on the local storage item. We can see the user selected data stored in the form of key/value pairs.
The getItem(‘Key’) helps in retrieving the data stored In the database.
var output = localStorage.getItem('bgcolor');
The local storage area can be cleared by using the clear() function or removeItem(‘key’) function.
localStorage.removeItem("bgcolor");
Storage Events
When we set or remove data from the web storage, a storage event will be fired on the window object. We can add listeners to the event and handle the storage changes if required.
window.addEventListener('storage', storageEventHandler, false);
function storageEventHandler(event) {
applySetting();
}
So, now you can start using Web Storage to store user preferences, user info, session info etc.You can also try creating apps that can be used completely offline and the data stored during offline can be sent back to the server as a batch update when the user is online again.
NOTE:
Web Storage simply provides a key-value mapping, e.g. localStorage["name"] = username;. Unfortunately, present implementations only support string-to-string mappings, so you need to serialise and de-serialise other data structures. You can do so using JSON.stringify() and JSON.parse().