HTML Window sessionStorage Property

The HTML Window sessionStorage property allows us to store key/value pairs data in a web browser for one session only. The data is automatically deleted when the browser tab is closed, making it perfect for temporary data storage during a user's visit.

The sessionStorage is part of the Web Storage API and provides a way to store data locally within the user's browser with session-level persistence. Unlike localStorage, sessionStorage data does not persist across browser sessions.

Syntax

Following is the syntax to access the sessionStorage object −

window.sessionStorage

SessionStorage Methods

The sessionStorage object provides several methods for data manipulation −

// Store data
sessionStorage.setItem(key, value);

// Retrieve data
sessionStorage.getItem(key);

// Remove specific item
sessionStorage.removeItem(key);

// Clear all session storage
sessionStorage.clear();

// Get number of items
sessionStorage.length;

Basic SessionStorage Example

Following example demonstrates basic sessionStorage operations −

<!DOCTYPE html>
<html>
<head>
   <title>SessionStorage Basic Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>SessionStorage Basic Operations</h2>
   <button onclick="storeData()">Store Data</button>
   <button onclick="retrieveData()">Retrieve Data</button>
   <button onclick="clearData()">Clear Data</button>
   <div id="output" style="margin-top: 20px; padding: 10px; background-color: #f0f0f0;"></div>

   <script>
      function storeData() {
         sessionStorage.setItem('username', 'John Doe');
         sessionStorage.setItem('email', 'john@example.com');
         document.getElementById('output').innerHTML = 'Data stored successfully!';
      }

      function retrieveData() {
         var username = sessionStorage.getItem('username');
         var email = sessionStorage.getItem('email');
         
         if (username && email) {
            document.getElementById('output').innerHTML = 
               'Username: ' + username + '<br>Email: ' + email;
         } else {
            document.getElementById('output').innerHTML = 'No data found in sessionStorage';
         }
      }

      function clearData() {
         sessionStorage.clear();
         document.getElementById('output').innerHTML = 'SessionStorage cleared!';
      }
   </script>
</body>
</html>

The output shows buttons for storing, retrieving, and clearing sessionStorage data −

SessionStorage Basic Operations
[Store Data] [Retrieve Data] [Clear Data]

Output area shows results based on button clicks:
- "Data stored successfully!" after storing
- "Username: John Doe, Email: john@example.com" after retrieving
- "SessionStorage cleared!" after clearing

SessionStorage Form Data Example

Following example shows how to use sessionStorage to temporarily save form data −

<!DOCTYPE html>
<html>
<head>
   <title>SessionStorage Form Data</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>User Registration Form</h2>
   <form id="userForm">
      <p>
         <label>Name: </label>
         <input type="text" id="name" placeholder="Enter your name">
      </p>
      <p>
         <label>Age: </label>
         <input type="number" id="age" placeholder="Enter your age">
      </p>
      <p>
         <button type="button" onclick="saveForm()">Save to SessionStorage</button>
         <button type="button" onclick="loadForm()">Load from SessionStorage</button>
      </p>
   </form>
   <div id="message" style="margin-top: 20px; padding: 10px; background-color: #e8f5e8;"></div>

   <script>
      function saveForm() {
         var name = document.getElementById('name').value;
         var age = document.getElementById('age').value;
         
         if (name && age) {
            sessionStorage.setItem('formData', JSON.stringify({
               name: name,
               age: age
            }));
            document.getElementById('message').innerHTML = 
               'Form data saved! Close and reopen this tab to see it disappear.';
         } else {
            document.getElementById('message').innerHTML = 'Please fill all fields';
         }
      }

      function loadForm() {
         var savedData = sessionStorage.getItem('formData');
         if (savedData) {
            var data = JSON.parse(savedData);
            document.getElementById('name').value = data.name;
            document.getElementById('age').value = data.age;
            document.getElementById('message').innerHTML = 'Form data loaded from sessionStorage!';
         } else {
            document.getElementById('message').innerHTML = 'No saved data found';
         }
      }

      // Auto-load data when page loads
      window.onload = function() {
         loadForm();
      };
   </script>
</body>
</html>

This example demonstrates saving and loading complex data (JSON objects) in sessionStorage. The data persists during page refreshes but disappears when the tab is closed.

SessionStorage vs LocalStorage

Understanding the key differences between sessionStorage and localStorage −

SessionStorage LocalStorage
Data expires when the tab is closed Data persists until manually deleted
Separate storage for each tab/window Shared across all tabs of the same origin
Temporary session-based storage Permanent local storage
Limited to current browser session Survives browser restarts
Typical storage limit: ~5-10MB Typical storage limit: ~5-10MB

SessionStorage Shopping Cart Example

Following practical example shows sessionStorage used for a temporary shopping cart −

<!DOCTYPE html>
<html>
<head>
   <title>SessionStorage Shopping Cart</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Simple Shopping Cart (Session Only)</h2>
   
   <div>
      <h3>Products</h3>
      <button onclick="addToCart('Laptop', 999)">Add Laptop ($999)</button>
      <button onclick="addToCart('Mouse', 25)">Add Mouse ($25)</button>
      <button onclick="addToCart('Keyboard', 75)">Add Keyboard ($75)</button>
   </div>

   <div style="margin-top: 20px;">
      <h3>Cart Actions</h3>
      <button onclick="viewCart()">View Cart</button>
      <button onclick="clearCart()">Clear Cart</button>
   </div>

   <div id="cartDisplay" style="margin-top: 20px; padding: 15px; background-color: #f9f9f9; border: 1px solid #ddd;">
      Cart is empty
   </div>

   <script>
      function addToCart(product, price) {
         var cart = JSON.parse(sessionStorage.getItem('cart') || '[]');
         cart.push({ product: product, price: price });
         sessionStorage.setItem('cart', JSON.stringify(cart));
         
         document.getElementById('cartDisplay').innerHTML = 
            product + ' added to cart! Total items: ' + cart.length;
      }

      function viewCart() {
         var cart = JSON.parse(sessionStorage.getItem('cart') || '[]');
         if (cart.length === 0) {
            document.getElementById('cartDisplay').innerHTML = 'Cart is empty';
            return;
         }

         var total = 0;
         var cartHtml = '<h4>Cart Contents:</h4><ul>';
         
         cart.forEach(function(item) {
            cartHtml += '<li>' + item.product + ' - $' + item.price + '</li>';
            total += item.price;
         });
         
         cartHtml += '</ul><p><strong>Total: $' + total + '</strong></p>';
         document.getElementById('cartDisplay').innerHTML = cartHtml;
      }

      function clearCart() {
         sessionStorage.removeItem('cart');
         document.getElementById('cartDisplay').innerHTML = 'Cart cleared!';
      }

      // Load cart on page load
      window.onload = function() {
         viewCart();
      };
   </script>
</body>
</html>

This shopping cart example demonstrates how sessionStorage can maintain state during a browsing session but automatically clears when the tab closes.

SessionStorage Lifecycle Tab Opens Storage Created Data Stored & Retrieved Tab Closes Data Deleted New session starts Page refreshes maintain data All data lost automatically

Browser Compatibility

SessionStorage is supported in all modern browsers −

  • Chrome: Version 4.0+

  • Firefox: Version 3.5+

  • Safari: Version 4.0+

  • Internet Explorer: Version 8.0+

  • Edge: All versions

Common Use Cases

SessionStorage is ideal for −

  • Form data backup − Temporarily saving form inputs to prevent data loss during page refreshes

  • Shopping carts − Maintaining cart contents during a browsing session

  • User preferences − Storing temporary UI settings like theme or language for the current session

  • Multi-step forms − Saving progress across multiple form pages

  • Temporary tokens − Storing session-specific authentication tokens

Conclusion

The sessionStorage property provides an efficient way to store temporary data

Updated on: 2026-03-16T21:38:54+05:30

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements