Horje
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:

  • Step 1: Go to the developer console (F12 in Chrome),
  • Step 2:Then choose the Application tab.
  • Step 3: In the Application Tab, we can see the Storage Menu.
  • Step 4: In the Storage Menu, we can look at different types of storage and their data, as seen in the below picture.

devconsole

Memory Capacity

  • Session Storage: 5 MB
  • Local Storage: 10 MB

Features of Session Storage :

  • SessionStorage is used to store the session information of the user.
  • A session is started when a user login or after visiting a web page.
  • This session is said to be ended when the user signs out or closes the tab.
  • Data persists if a page refreshes.
  • This session storage data is automatically cleared by the browser when a session is ended.
  • Data is stored in the form of key-value pairs.
  • Each tab has its own session Storage. Other tabs or windows, even the same website or origin cannot access this data.
  • Depending upon the browser, storage limit for a origin(domain + port + protocol) will be up to 5 MB on each tab.

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?

  • We want to store data only for a session.
  • We want to maintain sessions.
  • When dealing with transactions and sensitive information.
  • When we do not want other tabs or windows to access or share the information.
  • When we want the data to be erased when the session ends.

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

HTML
<!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() {
            let username = sessionStorage.getItem("username");
            let 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() {
            let length = sessionStorage.length;
            document.getElementById("output").textContent = "Session Storage length: "
                + length;
        }

        // Function to get Session Storage data by index
        function getSessionKey(index) {
            let key = sessionStorage.key(index);
            let 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:

  • LocalStorage is used to store the information of the user persistently in the browser.
  • It does not get cleared unless JavaScript code running on that website deletes it or we erase it using browser settings.
  • Data stored in local storage is not sent for the server upon every request.
  • Data is not lost even if we close the browser, or restart the computer.
  • Data is stored in the form of key- value pairs.
  • The web pages from the same origin in the other tabs/windows can also use this local storage data.
  • Depending upon the browser, storage limit for a origin(domain + port + protocol) will be up to 10 MB.

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?

  • We want to store data persistently.
  • When we do not want to lose data if the tab or browser is closed.
  • Want to store user activity and track user actions.
  • Need not maintain sessions.
  • Other tabs or windows can access the stored data, which can be shared with other tabs or windows with the same origin.

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

HTML
<!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) {
            let output = document.getElementById("output");
            let existingContent = output.innerHTML;
            output.innerHTML = existingContent + "<br>" + content;
        }

        // Function to set data in Local Storage
        function setLocalData() {
            localStorage.setItem("name", "Alice");
            let 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() {
            let name = localStorage.getItem("name");
            let 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() {
            let length = localStorage.length;
            appendToOutput("Local Storage length: " + length);
        }

        // Function to get Local Storage data by index
        function getLocalKey(index) {
            let key = localStorage.key(index);
            let 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..




Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
How to Find and Fix Broken Packages on Linux? How to Find and Fix Broken Packages on Linux?
Uninstall Node.JS Using Linux Command Line Uninstall Node.JS Using Linux Command Line
Best Linux distros of 2023 Best Linux distros of 2023
Best Text Editor for Kali Linux Best Text Editor for Kali Linux
How to Delete Multiple Lines in Vi editor How to Delete Multiple Lines in Vi editor

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14