Lesson 53 - JavaScript sessionStorage
The sessionStorage API is similar to localStorage, but data stored in sessionStorage is only available for the duration of the page session (until the browser is closed).
Key Differences Between localStorage and sessionStorage
| Feature | localStorage |
sessionStorage |
|---|---|---|
| Data Persistence | Persists even after closing the browser | Removed when the browser/tab is closed |
| Scope | Available across multiple tabs/windows | Available only within the same tab |
| Storage Limit | ~5MB | ~5MB |
Storing Data in sessionStorage
sessionStorage.setItem("username", "JohnDoe");
- Stores
"JohnDoe"under the key"username".
Retrieving Data from sessionStorage
let user = sessionStorage.getItem("username");
console.log(user); // Output: JohnDoe
- Retrieves the stored value.
Removing Data from sessionStorage
sessionStorage.removeItem("username"); // Deletes the "username" key
- Deletes
"username"from storage.
Clearing All sessionStorage Data
sessionStorage.clear();
- Removes all stored data in
sessionStorage.
Example: Saving User Preferences for a Single Session
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lesson 53 - sessionStorage</title>
</head>
<body>
<h2>Welcome, <span id="userDisplay"></span></h2>
<button onclick="logout()">Logout</button>
<script>
sessionStorage.setItem("username", "Alice");
document.getElementById("userDisplay").textContent = sessionStorage.getItem("username");
function logout() {
sessionStorage.removeItem("username");
location.reload();
}
</script>
</body>
</html>
- Stores
"Alice"as the username and removes it when clicking "Logout."
Try Your Hand
- Create a page that stores and retrieves a user's theme preference (light/dark mode) using
sessionStorage. - Create a login page where a username is stored in
sessionStorageand disappears when the tab is closed. - Build a shopping cart demo where items are temporarily saved in
sessionStorageuntil checkout.
Key Takeaways
sessionStoragestores data only for the session (until the tab is closed).- Use it for temporary data that should not persist across multiple visits.
- Use
sessionStorage.setItem(),getItem(),removeItem(), andclear()to manage stored values.