Html Web Storage


The Web Storage API is a new feature added into HTML5. It provides flexibility to save the data in browser locally. Data can be stored in key/value pair.

It is a simple API that is responsible to store and retrieve data from local storage. The storage size limit depends on the system configuration and type of browser.


Type of Web Storage

There are two type of Web Storage are as follows.


1. sessionStorage: It creates separate storage for each given origin that's available as long as the browser is open. Once the browse is closed data will go away and can not be recovered.


2 localStorage: localStorage is the same as sessionStorage. Data will persist even after close/reopening the browser. There is no expiration date for stored data. Data can be deleted by clearing the browser cache/locally stored data. The storage limit is more than sessionStorage.

Tip: The localStorage and sessionStorage can be used via Window.sessionStorage and Window.localStorage. They both have same kind of fucntions to store/retrieve/clear data.

Web storage methods and properties.

Both web storage provide same methods and properties to save, fetch and delete the data.

setItem(key,value): This method is used to store key/value data. It takes two parameter key and value.

getItem(key): This method is used to fetch stored data on basis of key.

removeItem(key): Delete stored data on basis of key.

clear(): When you want to remove entire data from storage.

key(index): Fetch the key on a given position.

length: It returns the number of stored items.


Difference between Web Storage and Cookies


Web Storage Cookies
The storage limit depends on the hardware configuration. It has the ability to store more data. We can save max 4KB data.
Stored data will never transfer to the server with HTTP request. Stored data will always transfer to the server with HTTP request which could be cause poor performance
Easy to store/retrive data It's complicated store/retrive data.
The storage is bound to the origin, different origin can not access stored data. Data is shared to all tabs and origins.

Example:

// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Save data to sessionStorage
localStorage.setItem('key', 'value');
// Get saved data from sessionStorage
let data = sessionStorage.getItem('key');
// Get saved data from localeStorage
let data = localStorage.getItem('key');
// Remove saved data from sessionStorage
sessionStorage.removeItem('key');
// Remove saved data from localeStorage
localStorage.removeItem('key');
// Remove all saved data from sessionStorage
sessionStorage.clear();
// Remove all saved data from localeStorage
localStorage.clear();

Object-like access

// sessionStorage: Set key
sessionStorage.test=1; // sessionStorage: get value
let value=sessionStorage.test;
// localStorage: set key
localStorage.test=1; // localStorage: get value let value=localStorage.test;

Note: key is user-generated, it can be anything, like string, integer or any dynamic user generated value.

Looping over keys

As you have seen, the methods get/set/remove the data by key. But if you want to get all saved values or keys, you will have to loop on storage arrays.

for(let i=0; i<localStorage.length; i++) {
let key=localStorage.key(i);
console.log(`${key}: ${localStorage.getItem(key)}`);
}

If the key is same as web storage property like "setItem" or "getItem"..etc, You can filter those key by using hasOwnProperty.

for(let key in localStorage) {
if (!localStorage.hasOwnProperty(key)) {
continue; // kip keys like "setItem", "getItem" etc
}
console.log(`${key}: ${localStorage.getItem(key)}`);
}

Storage event

Whenever the data gets updated in localStorage or sessionStorage, a storage event triggers.

The event triggers on all window objects where the storage is accessible except the once trigger the update.

key: the Key that was changed

oldValue: Return the old value (null if the new key is added)..

newValue: Returns the new value (null if the key is deleted).

url: the url of the page where the update happened.

storageArea: Returns either localStorage or sessionStorage object where the update happened.


Summary

Web storage objects like localStorage and sessionStorage allow us to store the data in browser using key/value pairs.

  • Both key and value must be in string formate.
  • There is no expiration time for stored data.
  • Storage is bound to origin/domain.
  • The limit is 5MB or more than that depending on the browser/OS.