Javascript Browser Local Storage

Code Snippets Browser Local Storage


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.


//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.
//Remove data by key.


//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.
//Remove data by key.


Resulting output:

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

Leave a Reply

Your email address will not be published. Required fields are marked *

The reCAPTCHA verification period has expired. Please reload the page.
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