HTML SessionStorage
What is SessionStorage in HTML5?
SessionStorage is a web storage feature in HTML5 that allows web applications to store key-value pairs in a web browser for the duration of the page session. Data stored in SessionStorage is only available within the same tab or window and is cleared when the tab or window is closed.
How do you access SessionStorage in JavaScript?
You can access SessionStorage using the sessionStorage object, which provides methods to store, retrieve, and remove items, similar to LocalStorage.
sessionStorage.setItem('key', 'value'); // Store data
const value = sessionStorage.getItem('key'); // Retrieve data
sessionStorage.removeItem('key'); // Remove data
sessionStorage.clear(); // Clear all data
What is the difference between LocalStorage and SessionStorage?
The key differences between LocalStorage and SessionStorage are:
- Scope: LocalStorage data persists even after the browser is closed, while SessionStorage data is only available for the duration of the page session.
- Storage Limits: Both have similar size limits, typically around 5-10MB per origin, but the data in SessionStorage is not shared across tabs or windows.
- Use Cases: LocalStorage is suitable for storing data that should persist across sessions, while SessionStorage is ideal for temporary data, such as user input during a single session.
How do you check if SessionStorage is supported in the browser?
You can check if SessionStorage is supported in the browser by verifying if the sessionStorage object is available:
if (typeof(Storage) !== "undefined") {
console.log("SessionStorage is supported!");
} else {
console.log("SessionStorage is not supported.");
}
How can you store an object in SessionStorage?
Since SessionStorage can only store strings, you need to convert an object to a string format (e.g., using JSON) before storing it and parse it back when retrieving it.
const user = { name: 'Alice', age: 30 };
sessionStorage.setItem('user', JSON.stringify(user)); // Store object
const retrievedUser = JSON.parse(sessionStorage.getItem('user')); // Retrieve object
console.log(retrievedUser.name); // Outputs: Alice
How do you iterate over items in SessionStorage?
You can iterate over items in SessionStorage using a for loop with the length property and the key() method to access each item:
for (let i = 0; i < sessionStorage.length; i++) {
const key = sessionStorage.key(i);
const value = sessionStorage.getItem(key);
console.log(`${key}: ${value}`);
}
How can you handle data expiration in SessionStorage?
SessionStorage does not support automatic expiration of data. To handle expiration, you can store a timestamp alongside the data and check it upon retrieval. If the current time exceeds the stored timestamp, you can remove the item from SessionStorage.
const expirationTime = 60 * 60 * 1000; // 1 hour in milliseconds
const data = { value: 'some data', timestamp: Date.now() + expirationTime };
sessionStorage.setItem('data', JSON.stringify(data));
function getData() {
const storedData = JSON.parse(sessionStorage.getItem('data'));
if (storedData && Date.now() < storedData.timestamp) {
return storedData.value; // Valid data
} else {
sessionStorage.removeItem('data'); // Expired data
return null;
}
}
What are some best practices for using SessionStorage?
Best practices for using SessionStorage include:
- Limit the amount of data stored to stay within browser limits.
- Use meaningful keys for easy identification of data.
- Consider security and avoid storing sensitive information in SessionStorage.
- Implement a strategy for data cleanup to avoid excessive memory use.
- Use JSON for complex data structures.
Can you share SessionStorage data across different tabs?
No, SessionStorage data is specific to the tab or window that created it. Each tab has its own SessionStorage, and data cannot be shared across tabs or windows, even if they are from the same origin.
How do you clear all data from SessionStorage?
You can clear all data from SessionStorage by using the clear() method, which removes all key-value pairs stored in the SessionStorage for the current origin.
sessionStorage.clear(); // Clears all data