{

Learn HTML5 Web Storage API tutorials


What is Web storage API in HTML5?

Web Storage is a process of storing user-specific content on the client-side in web applications. Content is stored in a form of keys and values. It introduces as part of The HTML5 API Specification.

Before that, the content will be stored on the client-side using cookies and Session Cookie. A cookie is a client-side object with an expiry time set. and It has some disadvantages.

You can also check my previous post about Local and Session Storage in Angular Web storage is more secure and more data is saved to the browser compared with cookies.

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

With these disadvantages, Web Storage API is introduced in HTML5. Web storage has more amount of data storage compared with cookies per domain. This stores application local data on the client-side without affecting server performance.

What are the types of web storage in HTML5?

As part of 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 if the browser is closed.
  • SessionStorage Data stored in sessionStorage has a scope of the session only. when the browser closes, session data will be lost and data will be deleted automatically.
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 APIs inherit Window objects 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 no support. we have to use the cookie as an alternative mechanism.

  
if(Window.sessionStorage){  
  
// Supports Session Storage  
}else { // support not available  
}  

Web storage provides different API 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
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 the value for the existing key
removeItem() key is passed, delete the key and value from storage object
clear() This method removes entire cache data and empty it
keys() number is passed and returned key of that number position in storage

Is sessionStorage shared between tabs?

data stored in SessionStorage are not shared between tabs. data stored to the life of the tab. data will be expired after the session expires. The session expired when the tab is closed.

If you want to share data among multiple tabs, localstroage can be used.

Does HTML5 support offline storage?

offline storage is the process of saving data in a browser and allows it to use in applications running browsers without an internet connection.

It is useful in Progressive web applications as well as low 2g devices to work. It helps applications to send data once the internet is available.

Following are some examples in javascript with local and session storage API

How to add JSON object to Localstorage?

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.

The below example stores JSOn object to local storage in Browser.

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)  

How to check Localstorage data in Browser?

Follow are the steps to check storage data To test the data storage,

  • Goto DevTools -> Application tab -> storage section (please see below screenshot for more information) LocalStorage SessionStorage SetItem

How to retrieve data from web storage?

There are two ways we can retrieve data from web storage Can use the getItem method or with the name of the key as seen below

var empdata = localstorage.getItem("empdata");
var empdata = localstorage.empdata;

how to delete data from webstorage?

Data from web storage can be removed using the removeItem() method or delete object syntax

localstorage.removeItem("empdata");
delete localstorage.empdata;

and also we can clear data from storage using the clear() method

localstorage.clear();

How to View/test the storage data in Chrome:-

Here are the steps and you can see the above screenshot for the same

  • Open developer tools
  • Select the Application tab
  • Go to the Storage tab, you will see LocalStorage and SessionStorage under it

How to check storage in Firefox?

In Firefox, You can inspect the elements using either an inbuilt firefox console or Firebug

  • Go to Inspect Element option either right-click on the browser or use Tools + web developer + inspector
  • Go to the Storage tab
  • You will see different storage tabs as shown in the below screenshot
Webstorage Firefox test

Fixing QUOTA_EXCEEDED_ERR for web storage?

Sometimes, We used to get “uncaught_error: QUOTA_EXCEEDED_ERROR” due to data storage capacity being exceeded.

To Fix it this issue, we have two ways

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

Here is the code to handle QUOTA_EXCEEDED_ERROR using try and catch in javascript

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

Does Web storage offline has a limit?

web storage API has a limit on the amount of data stored during offline storage.

The size limit depends on browsers.

Firefox, Safari, and Chrome have a maximum of 5MB of data. Internet Explorer has a maximum of 10MB of data.

Conclusion

You learned the following things in web storage API

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.