JavaScript BOM window.sessionStorage object


The window.sessionStorage object is part of the Web Storage API in JavaScript and provides a mechanism for storing data for the duration of a session in the user's web browser. Unlike localStorage, which persists data even after the browser is closed, sessionStorage data is only available for the duration of the page session, meaning it lasts as long as the browser tab or window is open. When the tab or window is closed, the data stored in sessionStorage is deleted.

Key Features of window.sessionStorage

  1. Accessing sessionStorage:

    • The sessionStorage object can be accessed directly via window.sessionStorage.

    • console.log(sessionStorage); // Logs the sessionStorage object
  2. Properties and Methods: The sessionStorage object includes several methods and properties for managing stored data:

    • sessionStorage.setItem(key, value): Adds a key-value pair to sessionStorage. If the key already exists, its value is updated.

      sessionStorage.setItem('username', 'john_doe'); // Sets the key 'username' with the value 'john_doe'
    • sessionStorage.getItem(key): Retrieves the value associated with the specified key. If the key does not exist, it returns null.

      const username = sessionStorage.getItem('username'); console.log(username); // Logs 'john_doe'
    • sessionStorage.removeItem(key): Removes the specified key and its associated value from sessionStorage.

      sessionStorage.removeItem('username'); // Removes the key 'username'
    • sessionStorage.clear(): Clears all key-value pairs in sessionStorage.

      sessionStorage.clear(); // Removes all items from sessionStorage
    • sessionStorage.length: Returns the number of key-value pairs currently stored in sessionStorage.

      console.log(sessionStorage.length); // Logs the number of items in sessionStorage
    • sessionStorage.key(index): Returns the name of the key at the specified index in the sessionStorage.

      console.log(sessionStorage.key(0)); // Logs the first key in sessionStorage
  3. Data Types:

    • Similar to localStorage, data stored in sessionStorage is always stored as strings. If you need to store objects or arrays, you should use JSON.stringify() to convert them to strings before storing, and JSON.parse() to convert them back to their original form when retrieving.
    • Example:
      const user = { name: 'John', age: 30 }; sessionStorage.setItem('user', JSON.stringify(user)); // Store object as string const retrievedUser = JSON.parse(sessionStorage.getItem('user')); // Convert back to object console.log(retrievedUser); // Logs: { name: 'John', age: 30 }
  4. Limitations:

    • sessionStorage has a storage limit (typically around 5-10 MB, depending on the browser).
    • Data stored in sessionStorage is session-specific. It is accessible only to the pages that are opened in the same tab or window, and cannot be accessed by different tabs or windows, even if they are from the same origin.

Example Usage

Here’s a simple example demonstrating how to use window.sessionStorage to store and retrieve user input for a temporary session:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>SessionStorage Example</title> </head> <body> <h1>Session Storage Example</h1> <input type="text" id="username" placeholder="Enter your username"> <button id="saveButton">Save Username</button> <button id="loadButton">Load Username</button> <button id="clearButton">Clear Session Storage</button> <p id="output"></p> <script> document.getElementById('saveButton').addEventListener('click', function() { const username = document.getElementById('username').value; sessionStorage.setItem('username', username); // Save username to sessionStorage alert('Username saved for this session!'); }); document.getElementById('loadButton').addEventListener('click', function() { const username = sessionStorage.getItem('username'); // Retrieve username from sessionStorage document.getElementById('output').innerText = username ? `Username: ${username}` : 'No username found in this session!'; }); document.getElementById('clearButton').addEventListener('click', function() { sessionStorage.removeItem('username'); // Clear username from sessionStorage alert('Username cleared for this session!'); }); </script> </body> </html>

Summary

The window.sessionStorage object is a powerful tool in the Web Storage API that enables developers to store key-value pairs for the duration of a page session. This feature is useful for managing temporary data, such as user input or session-specific settings, without the need for cookies or server-side storage. Its session-specific nature makes it ideal for scenarios where data should not persist once the tab or window is closed, enhancing user privacy and providing a smoother user experience.