Javascript session storage
Created By: chatGPT
Session Storage is a web storage solution that allows you to store data for a single session. Each tab or window opened in a web browser has its own session storage space. This means the data is specific to one tab and persists as long as the tab is open. Once the tab is closed, the stored data is cleared. This is particularly useful for temporary data storage, such as form data or user preferences during a browsing session.
sessionStorage.setItem('key', 'value');
// To retrieve data:
let value = sessionStorage.getItem('key');
// To remove data:
sessionStorage.removeItem('key');
// To clear all session storage:
sessionStorage.clear();
You can store data using the
setItem
method and retrieve it using the getItem
method. Here’s a complete example showcasing how to use session storage in a web application.// Storing user information
function storeUserData() {
let userName = 'John Doe';
sessionStorage.setItem('userName', userName);
}
// Retrieving user information
function getUserData() {
let userName = sessionStorage.getItem('userName');
console.log('User Name:', userName);
}
// Removing user information
function removeUserData() {
sessionStorage.removeItem('userName');
}
Limitations of session storage include a size limit (usually around 5-10MB), and it should not be used for sensitive data unless properly encrypted. Since session storage is specific to the session, it is not shared across tabs.
// Example of checking availability
if (typeof(Storage) !== 'undefined') {
console.log('Session storage is available.');
} else {
console.log('Session storage is not supported.');
}