Open In App

How to save data in session and local storage ?

SessionStorage and LocalStorage are the two most important ways to store data in the browser. SessionStorage is the temporary storage that web applications use to store data, whereas LocalStorage is the persistent storage that websites use to manage our data. These storages reside in the browser’s memory.

Apart from these storage browser also stores information in Cookies. A Cookie is just some textual information about website. Cookies help to make the browsing experience better. Cookies are website specific and hold the information of frequently visited websites



Steps to open Session Storage and Local Storage:

Memory Capacity

Features of Session Storage :

Example: We visited a site A in Tab 1 , and the same site in Tab 2, each tab has it’s own session storage up to 5 Mb. Other web pages from the same origin can use this data in that session.



When to use Session Storage?

Methods of session storage object

sessionstorage.setItem(key,value); // Adds data in key-value pair
sessionstorage.getItem(key);       // Gets the data for the given key
sessionStorage.removeItem(key);    // Removes the (key, value) pair data for the given key
sessionstorage.key(index);         // Gets the key based on the index position
sessionstorage.length;             // Returns the length of the storage list.
sessionstorage.clear();            // Clears all the session storage

Demonstrating Session Storage

Example: The following example demonstrates session storage




<!DOCTYPE html>
<html>
<head>
    <title>Session Storage Example</title>
</head>
<body>
    <h1>Session Storage Example</h1>
  
    <button onclick="setSessionData()">Set Session Data</button>
    <button onclick="getSessionData()">Get Session Data</button>
    <button onclick="clearSessionData()">Clear Session Data</button>
    <button onclick="getSessionLength()">Get Session Length</button>
    <button onclick="getSessionKey(1)">Get Session Data by Index</button>
  
    <div id="output"></div>
  
    <script>
        // Function to set data in Session Storage
        function setSessionData() {
            sessionStorage.setItem("username", "JohnDoe");
            sessionStorage.setItem("preferences", JSON.stringify({ 
                                                          theme: "dark", lang: "en" }));
        }
  
        // Function to retrieve data from Session Storage
        function getSessionData() {
            var username = sessionStorage.getItem("username");
            var preferences = JSON.parse(sessionStorage.getItem("preferences"));
  
            document.getElementById("output").textContent =
                "Username: " + username + ", Preferences: " + JSON.stringify(preferences);
        }
  
        // Function to clear all data from Session Storage
        function clearSessionData() {
            sessionStorage.clear();
            document.getElementById("output")
                      .textContent = "Session Storage data cleared.";
        }
  
        // Function to get the length of Session Storage
        function getSessionLength() {
            var length = sessionStorage.length;
            document.getElementById("output").textContent = "Session Storage length: "
                                                              + length;
        }
  
        // Function to get Session Storage data by index
        function getSessionKey(index) {
            var key = sessionStorage.key(index);
            var value = sessionStorage.getItem(key);
            document.getElementById("output").textContent =
                "Key at index " + index + ": " + key + ", Value: " + value;
        }
    </script>
</body>
</html>

Output: In the left side of the screen, we are clicking on buttons which adds the data , modifies the data in sessionstorage and in the right side under application tab, we can see how this sessionstorage is getting modified.

Features of LocalStorage:

Example: We visited a site in Tab 1 and the same site in Tab 2 or another window. We stored some data from each tab or window; they are centrally stored at the same place (unlike for sessionstorage, where each tab has its own storage even though the origin is the same) and can be accessed from all the web pages originating from the same origin in the same tab.

When to use LocalStorage?

The browser provides local storage and session storage objects to work with. We use the objects to store and manage the data.

Methods of localstorage object

localStorage.setItem(key,value); // Adds data in key-value pair
localStorage.getItem(key);       // Gets the data for the given key
localStorage.removeItem(key);    // Removes the (key, value) pair data for the given key
localStorage.key(index);         // Gets the key based on the index position
localStorage.length;             // Returns the lenght of the storage list
localStorage.clear();            // Clears all the local storage associated with the origin.        

Demonstrating LocalStorage Object

Example: The following example demonstrates Local Storage object




<!DOCTYPE html>
<html>
<head>
    <title>Local Storage Example</title>
</head>
<body>
    <h1>Local Storage Example</h1>
  
    <button onclick="setLocalData()">Set Local Data</button>
    <button onclick="getLocalData()">Get Local Data</button>
    <button onclick="clearLocalData()">Clear Local Data</button>
    <button onclick="getLocalLength()">Get Local Length</button>
    <button onclick="getLocalKey(0)">Get Local Data by Index</button>
  
    <div id="output"></div>
  
    <script>
        // Function to append content to output
        function appendToOutput(content) {
            var output = document.getElementById("output");
            var existingContent = output.innerHTML;
            output.innerHTML = existingContent + "<br>" + content;
        }
  
        // Function to set data in Local Storage
        function setLocalData() {
            localStorage.setItem("name", "Alice");
            var preferences = { theme: "light", lang: "fr" };
            localStorage.setItem("preferences", JSON.stringify(preferences));
            appendToOutput("Local data set: Name: Alice, Preferences: " + JSON.stringify(preferences));
        }
  
        // Function to retrieve data from Local Storage
        function getLocalData() {
            var name = localStorage.getItem("name");
            var preferences = JSON.parse(localStorage.getItem("preferences"));
            appendToOutput("Local data retrieved: Name: " + name + ", Preferences: " + JSON.stringify(preferences));
        }
  
        // Function to clear all data from Local Storage
        function clearLocalData() {
            localStorage.clear();
            appendToOutput("Local Storage data cleared.");
        }
  
        // Function to get the length of Local Storage
        function getLocalLength() {
            var length = localStorage.length;
            appendToOutput("Local Storage length: " + length);
        }
  
        // Function to get Local Storage data by index
        function getLocalKey(index) {
            var key = localStorage.key(index);
            var value = localStorage.getItem(key);
            appendToOutput("Key at index " + index + ": " + key + ", Value: " + value);
        }
    </script>
</body>
</html>

Output: In the left side of the screen, we are clicking on buttons which adds the data , modifies the data in localstorage and in the right side under application tab, we can see how this localstorage is getting modified..

Demonstration of LocalStorage Implementation


Article Tags :