For the longest time cookies were the only way to maintain state. Then HTML5 came. HTML5 provides two more ways of storing data on the browser - localStorage and sessionStorage.
LocalStorage stores the data with no expiration date. It means the data will not be deleted when the browser is closed, and the data will be available the next day, next week, or even next year.
In chrome browser we can see the contents of localStorage by opening
Developer tools > Application > Local Storage.
Setting, retrieving and deleting data from localStorage is pretty easy.
1localStorage.setItem("favoriteColor", "black"); 2localStorage.favoriteColor 3localStorage.removeItem("favoriteColor");
Local storage provides at least 5MB of data storage across all major web browsers. This a lot more than the 4KB (maximum size) that we can store in cookies.
Data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Closing a tab/window ends the session and clears objects in sessionStorage.
1// Save data to sessionStorage 2sessionStorage.setItem('key', 'value'); 3 4// Get saved data from sessionStorage 5let data = sessionStorage.getItem('key'); 6 7// Remove saved data from sessionStorage 8sessionStorage.removeItem('key'); 9 10// Remove all saved data from sessionStorage 11sessionStorage.clear();