About
In this code snippet, we’ll learn how to access the browser local storage with Javascript.
If you have the need to store the users data locally on their browser you can utilize session or local storage. Session storage will store data until the window is closed meanwhile local storage will keep the data even after the browser is closed. Other than that they are the same.
Note: This type of storage is more appropriate for key-value pairs. If you need to store larger data like files using IndexedDB.
Let’s see the example below.
Code:
//Local storage////////////////////////////////////// //Local storage stays in the browser even after it's closed. //Add data as key value pair. localStorage.setItem("userName", "Bob"); //Get data by key. console.log(localStorage.getItem("userName")); //Remove data by key. localStorage.removeItem("userName"); ///////////////////////////////////////////////////// //Session storage//////////////////////////////////// //Local storage is clared when the browser is closed. //Add data as key value pair. sessionStorage.setItem("userName", "Bob"); //Get data by key. console.log(sessionStorage.getItem("userName")); //Remove data by key. sessionStorage.removeItem("userName"); /////////////////////////////////////////////////////