Horje
JavaScript sessionStorage

JavaScript sessionStorage is a web storage technique that stores data for the duration of a page session. The sessionStorage object lets you store key/value pairs in the browser. It allows setting, retrieving, and managing data that persists only until the browser tab or window is closed, ensuring data accessibility within the same tab.

Syntax

window.sessionStorage;

Methods of sessionStorage

MethodDescription
setItem(key, value)Sets the data in the sessionStorage with the passed key and value.
getItem(key)Returns the value of the key passed to it, if it is stored in the storage.
removeItem(key)Removes the passed key with its value from the storage.
storage.lengthReturns the total number of stored items in the storage.
key(index)Returns the key stored at the passed index.
clear()Clears all the stored items.

Key Features of JavaScript sessionStorage

  • Temporary Storage: Data is stored only for the duration of the session.
  • Tab-Specific: Data is accessible only within the same browser tab or window.
  • Simple API: Provides straightforward methods for setting, getting, and removing items.
  • Persistent During Reloads: Data persists across page reloads within the same session.
  • Storage Limit: Typically offers around 5MB of storage per origin for session data.

Example: Using sessionStorage with JavaScript

In this example, sessionStorage is used to store, retrieve, and remove key-value pairs. Buttons trigger functions that either set, get, or remove items from sessionStorage, with results displayed in an HTML element.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <title>
        JavaScript innerHTML
    </title>
    <style>
        #container {
            text-align: center;
        }
    </style>
</head>

<body>
    <div id="container">
        <h1 style="color: green;">
            GeeksforGeeks
        </h1>
        <h2>
            Click the below buttons to set, retrieve and <br />
            remove the stored values from the sessionStorage.
        </h2>
        <label for="nameInp">Enter Key for Storage:</label><br />
        <input type="text" id="nameInp"><br /><br />
        <label for="emailInp">Enter Value for Storage:</label><br />
        <input type="text" id="emailInp">
        <p id="result"></p>
        <button id="setBtn">Set Item</button>
        <button id="getBtn">Get Item</button>
        <button id="removeBtn">Remove Item</button>
    </div>

    <script>
        const setBtn = document.getElementById('setBtn');
        const getBtn = document.getElementById('getBtn');
        const removeBtn = document.getElementById('removeBtn');
        const result = document.getElementById('result');
        function setItemHandler() {
            sessionStorage.clear();
            const nameInpText =
                document.getElementById('nameInp').value;
            const emailInpText =
                document.getElementById('emailInp').value;
            if (emailInpText && nameInpText) {
                sessionStorage.setItem(nameInpText, emailInpText);
                result.innerHTML = " ";
            }
            else {
                result.innerHTML = `
                    <b style='color: red'>
                        Input fields can not be empty!
                    </b>`;
            }
        }

        function getItemHandler() {
            const nameInpText =
                document.getElementById('nameInp').value;
            const emailInpText =
                document.getElementById('emailInp').value;
            if (emailInpText && nameInpText) {
                result.innerHTML = `
                    <b style='color: green'>
                        Stored Item: ${sessionStorage.getItem(nameInpText)}
                    </b>`;
            }
            else {
                result.innerHTML = `
                    <b style='color: red'>
                        No item is stored in storage!
                    </b>`;
            }

        }

        function removeItemHandler() {
            const nameInpText =
                document.getElementById('nameInp').value;
            sessionStorage.removeItem(nameInpText);
            console.log(sessionStorage.removeItem(nameInpText));
            if (sessionStorage.removeItem(nameInpText) === undefined) {
                result.innerHTML = `
                    <b style='color: green'>
                        Item is removed Successfully!!
                    </b>`;
            }
            else {
                result.innerHTML = `
                    <b style='color: red'>
                        An Error Occured, can not remove item!!
                    </b>`;
            }
        }

        setBtn.addEventListener('click', setItemHandler)
        getBtn.addEventListener('click', getItemHandler)
        removeBtn.addEventListener('click', removeItemHandler)
    </script>
</body>

</html>

Output:

Conclusion

JavaScript sessionStorage is a powerful tool for temporarily storing data within a user’s session. It provides simple methods to set, retrieve, and manage key-value pairs, ensuring information is available until the browser tab closes. Using sessionStorage enhances user experience by maintaining state and preferences throughout the session.

JavaScript sessionStorage FAQs

1. Does sessionStorage data persist across page reloads?

Yes, data stored in sessionStorage persists across page reloads but is cleared when the tab or window is closed.

2. What is the difference between sessionStorage and localStorage?

sessionStorage stores data for the duration of the page session and is cleared when the tab or window is closed. localStorage, on the other hand, stores data persistently until it is explicitly deleted.

3. Can sessionStorage store objects?

Yes, but you need to serialize the object to a string using JSON.stringify() before storing, and deserialize it using JSON.parse() when retrieving.

4. Is sessionStorage shared across tabs?

No, sessionStorage is unique to each tab or window. Data stored in sessionStorage is not shared across different tabs or windows.

5. How can I clear specific data from sessionStorage?

To remove a specific item, use the removeItem method with the key of the item you want to remove.

sessionStorage.removeItem(‘key’);




Reffered: https://www.geeksforgeeks.org


JavaScript

Related
JavaScript onclick Event JavaScript onclick Event
Convert a String to Number in JavaScript Convert a String to Number in JavaScript
How to Clone a Set in JavaScript ? How to Clone a Set in JavaScript ?
What is Map Coercion in JavaScript ? What is Map Coercion in JavaScript ?
Can a Map use Functions as Keys? Can a Map use Functions as Keys?

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