Monday, July 23, 2018

Learn HTML5 Web Storage API tutorials

Web storage API introduction

Web Storage is a process of storing user specific content on the client side in web applications. Content will be stored in a form of key and values. This was introduced as part of HTML5 API Specification. Before that, content will be stored on the client side using cookies. Cookies have some disadvantages.

Disadvantages with cookies 


  • All browsers don't have support for cookies and client can configure to disable cookies, in that case, There is no way to store content on the client side
  • Limit the amount (4kb) of data stored in cookies
  • Every request has cookie data to be passed, so every request has duplicate cookie data, performance is not good.

Web storage has more amount of data storage compared with cookies per domain. This store application local data on the client side without affecting server performance.
As part HTML5, Two storage methods were introduced.
LocalStorage Data stored in localstorage has no expiry mechanism. Data will never be expired. data will not be lost even the browser is closed.
SessionStorage Data stored in sessionStorage has a scope of the session. when the browser closes, session data will be lost and data will be deleted automatically.

Difference between SessionStorage, LocalStorage, and Cookie

SessionStorage LocalStorage Cookies
Store up to 10MB data, Safar has 5MB only Store up to 10MB data, Safar has 5MB only Up to 4KB data
Store and data will be available for window/tab/session Store and data available for all windows/tabs/sessions Cookie has Expiry time to be set
Data deleted automatically after closing browser Data will not be deleted, Need to write a code to delete it manually Deleted after the Expiry time
Less support for legacy Browsers Less support for legacy Browsers Support old browsers also
How to check web storage support available in any browser? 
Web storage API's inherit Window object with two properties Window.sessionStorage and Window.localStorage Both will provide access to SessionStorage and LocalStorage. This piece of code needs to write to check in older browsers. if there is not support. we have to use the cookie as an alternative mechanism

if(Window.sessionStorage){

// Supports Session Storage
}else { // support not aivalble
}
Web storage provides different APIs methods and properties. Different methods/accessors methods are the same for both storage types Properties length - returns the number of data items stored in web storage methods
Method Description
getItem() key name is passed and returned the key's value
setItem() save the key and value, if the key already exists, update value for existing key
removeItem() key is passed, delete the key and value from storage
clear() This method removes entire cache data and empty it
keys() number is passed and returned key of that number position in a storage
Setting data into Web Storage setItem(key, value) method is used to store the data into storage. Here is an example for setting data into localStorage
const Emps = [
  {
    "id": "001",
    "name": "John",
  },
  {
    "id": "002",
    "name": "Francis",
  },
  {
    "id": "003",
    "name": "Ram",
  }
]

localStorage.setItem('empdata', JSON.stringify(Emps))
const empdata = JSON.parse(localStorage.getItem('empdata'))
console.log('Emps: ', empdata)
To test the data storage, Goto DevTools + Application tab + storage section (please see below screenshot for more information) LocalStorage SessionStorage SetItem Getting data from web storage
 to retrieve data from web storage use getItem ('key')
Remove specific key from web storage cache
 To delete specific data from web storage, use removeItem('key')
To remove entire data from the storage
 to delete all data from web storage, use clear()

View/test the storage data in Chrome:- 

Here are the steps and you can see the above screenshot for the same
1. Open developer tools
2. Select the Application tab
3. Go to storage tab, you will see LocalStorage and SessionStorage under it

View/test the storage in Firefox:- 

In Firefox, You can inspect the elements using either inbuilt firefox console or Firebug
1. Go to Inspect Element option either right click on the browser or using Tools + web developer + inspector
2. Go to Storage tab
3. You will see different storage tabs as shown in below screenshot

Webstorage Firefox test

Fixing QUOTA_EXCEEDED_ERR for web storage?

We used to get "uncaught_error: QUOTA_EXCEEDED_ERROR" sometimes due to data storage capacity is exceeded.

To Fix  it this issue, we have two ways

  1. Remove or reduce the size of items in Storage
  2. Always use exception handling using try/catch block to catch the runtime errors.

try {
  sessionStorage.setItem('key', 'value');
} catch (e) {
  if (e == QUOTA_EXCEEDED_ERROR) {
    console.log('Storage Limit is already full.');
  }
}