Open In App

JavaScript sessionStorage

Last Updated : 23 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.


Next Article
Article Tags :

Similar Reads