Javascript Browser Local Storage

Code Snippets Browser Local Storage
Share:

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");
/////////////////////////////////////////////////////

Resulting output:

Developer Tools(F12) > Application > Local/Session storage
Share:

Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger