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
Accessing
sessionStorage
:- The
sessionStorage
object can be accessed directly viawindow.sessionStorage
. console.log(sessionStorage); // Logs the sessionStorage object
- The
Properties and Methods: The
sessionStorage
object includes several methods and properties for managing stored data:sessionStorage.setItem(key, value)
: Adds a key-value pair tosessionStorage
. 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 returnsnull
.const username = sessionStorage.getItem('username'); console.log(username); // Logs 'john_doe'
sessionStorage.removeItem(key)
: Removes the specified key and its associated value fromsessionStorage
.sessionStorage.removeItem('username'); // Removes the key 'username'
sessionStorage.clear()
: Clears all key-value pairs insessionStorage
.sessionStorage.clear(); // Removes all items from sessionStorage
sessionStorage.length
: Returns the number of key-value pairs currently stored insessionStorage
.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 thesessionStorage
.console.log(sessionStorage.key(0)); // Logs the first key in sessionStorage
Data Types:
- Similar to
localStorage
, data stored insessionStorage
is always stored as strings. If you need to store objects or arrays, you should useJSON.stringify()
to convert them to strings before storing, andJSON.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 }
- Similar to
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.