Analytics choices

Analytics is optional. If allowed, Google measures public pages, navigation, recognized acquisition sources and engagement, including tool and playground use. The site excludes entered code, search terms and form contents from its Analytics events. You can withdraw here. This choice does not change advertising consent.

Read about Analytics and your information.

HTML Web Storage

Learn how to store data in the browser using localStorage and sessionStorage

The HTML Web Storage API provides two mechanisms for storing data on the client side: localStorage for persistent storage and sessionStorage for session-based storage. Both allow you to store data without using cookies.

What is Web Storage?

Web Storage holds string key/value pairs in the browser. It is not inherently more secure than cookies: same-origin scripts can read it. Capacity and availability depend on the browser and settings; handle storage failures and avoid storing secrets.

Key Benefits

  • More Storage: 5-10 MB vs 4 KB for cookies
  • Not sent automatically with HTTP requests: JavaScript can still read and transmit stored values.
  • Simple API: Easy to use key-value interface
  • Synchronous: No callbacks needed

localStorage vs sessionStorage

HTML Web Storage provides two storage objects with different lifetimes:

Feature localStorage sessionStorage
Lifetime Persists until explicitly deleted Cleared when tab/window closes
Scope Shared across all tabs/windows Limited to single tab/window
Storage Limit 5-10 MB (browser dependent) 5-10 MB (browser dependent)
Use Cases User preferences, settings, themes Form data, shopping cart, wizard

Checking for Storage Support

Always check if Web Storage is supported before using it:

Feature Detection

Unavailable or blocked: markup context “Matching lesson markup is not supplied; this fragment uses a generic HTML scaffold.”. Provide inline styles and scripts, embedded images or the missing HTML context. External requests and browser dialogs stay blocked.

if (typeof Storage !== "undefined") {
  // Web Storage is supported
  console.log("localStorage is available");
} else {
  // Web Storage is not supported
  console.log("Sorry, Web Storage is not supported");
}

Web Storage Methods

Both localStorage and sessionStorage have the same methods and properties:

Method/Property Description
setItem(key, value) Stores a key-value pair
getItem(key) Retrieves a value by key
removeItem(key) Removes a specific item
clear() Removes all items
key(index) Gets the key at a specific index
length Returns number of stored items

localStorage Examples

Basic localStorage Operations

// Store data
localStorage.setItem("username", "John Doe");
localStorage.setItem("email", "john@example.com");

// Retrieve data
var username = localStorage.getItem("username");
console.log(username); // "John Doe"

// Remove specific item
localStorage.removeItem("email");

// Clear all data
localStorage.clear();

// Check number of items
console.log(localStorage.length);

Storing Objects (JSON)

// Store object
var user = {
  name: "John Doe",
  age: 30,
  email: "john@example.com"
};

// Convert to JSON string before storing
localStorage.setItem("user", JSON.stringify(user));

// Retrieve and parse
var storedUser = JSON.parse(localStorage.getItem("user"));
console.log(storedUser.name); // "John Doe"

💡 Important

Web Storage can only store strings. Use JSON.stringify() to store objects and JSON.parse() to retrieve them.

sessionStorage Examples

Using sessionStorage

// Store temporary data
sessionStorage.setItem("cartItems", "3");
sessionStorage.setItem("currentPage", "checkout");

// Retrieve data
var items = sessionStorage.getItem("cartItems");
console.log(items); // "3"

// Data persists during page reload
location.reload(); // cartItems still available

// Data is cleared when tab closes
// (Open in new tab - data won't be there)

Form State Preservation

<form id="myForm">
  <input type="text" id="name" placeholder="Name">
  <input type="email" id="email" placeholder="Email">
  <button type="submit">Submit</button>
</form>

<script>
// Save form data on input
document.getElementById("name").addEventListener("input", function(e) {
  sessionStorage.setItem("formName", e.target.value);
});

document.getElementById("email").addEventListener("input", function(e) {
  sessionStorage.setItem("formEmail", e.target.value);
});

// Restore form data on page load
window.addEventListener("load", function() {
  var name = sessionStorage.getItem("formName");
  var email = sessionStorage.getItem("formEmail");

  if (name) document.getElementById("name").value = name;
  if (email) document.getElementById("email").value = email;
});

// Clear data on submit
document.getElementById("myForm").addEventListener("submit", function() {
  sessionStorage.removeItem("formName");
  sessionStorage.removeItem("formEmail");
});
</script>

Practical Examples

Dark Mode Toggle

<button onclick="toggleDarkMode()">Toggle Dark Mode</button>

<script>
// Check saved preference on load
window.addEventListener("load", function() {
  var darkMode = localStorage.getItem("darkMode");

  if (darkMode === "enabled") {
    document.body.classList.add("dark-mode");
  }
});

function toggleDarkMode() {
  document.body.classList.toggle("dark-mode");

  // Save preference
  if (document.body.classList.contains("dark-mode")) {
    localStorage.setItem("darkMode", "enabled");
  } else {
    localStorage.setItem("darkMode", "disabled");
  }
}
</script>

Visit Counter

<p>You have visited this page <span id="count">0</span> times.</p>

<script>
// Get current count or initialize to 0
var count = localStorage.getItem("visitCount") || 0;

// Increment count
count++;

// Store new count
localStorage.setItem("visitCount", count);

// Display count
document.getElementById("count").textContent = count;
</script>

Shopping Cart

// Shopping cart manager
var cart = {
  add: function(item) {
    var items = this.getItems();
    items.push(item);
    localStorage.setItem("cart", JSON.stringify(items));
  },

  remove: function(itemId) {
    var items = this.getItems();
    items = items.filter(function(item) {
      return item.id !== itemId;
    });
    localStorage.setItem("cart", JSON.stringify(items));
  },

  getItems: function() {
    var items = localStorage.getItem("cart");
    return items ? JSON.parse(items) : [];
  },

  clear: function() {
    localStorage.removeItem("cart");
  },

  getTotal: function() {
    var items = this.getItems();
    return items.reduce(function(total, item) {
      return total + item.price;
    }, 0);
  }
};

// Usage
cart.add({ id: 1, name: "Product 1", price: 29.99 });
cart.add({ id: 2, name: "Product 2", price: 49.99 });

console.log(cart.getItems());
console.log("Total: $" + cart.getTotal());

Storage Events

The storage event fires when a storage area changes (in another window/tab):

Listening for Storage Changes

window.addEventListener("storage", function(e) {
  console.log("Storage changed!");
  console.log("Key: " + e.key);
  console.log("Old value: " + e.oldValue);
  console.log("New value: " + e.newValue);
  console.log("URL: " + e.url);
  console.log("Storage area: ", e.storageArea);
});

// This event only fires in OTHER windows/tabs
// Changes in the same window don't trigger it

⚠️ Note

The storage event only fires in other windows/tabs with the same origin. It does NOT fire in the window that made the change.

Web Storage Best Practices

Best Practices

  1. Check for Support: Always verify Web Storage is available
  2. Handle Errors: Wrap storage operations in try-catch blocks
  3. Don't Store Sensitive Data: Never store passwords or tokens
  4. Use JSON for Objects: Convert objects to strings with JSON.stringify()
  5. Set Expiration: Implement your own expiration mechanism
  6. Validate Data: Always validate retrieved data
  7. Monitor Storage Size: Be aware of storage limits (5-10 MB)
  8. Clean Up: Remove unused data regularly
  9. Use Appropriate Storage: Choose localStorage vs sessionStorage wisely
  10. Namespace Keys: Use prefixes to avoid key collisions

Error Handling Example

Unavailable or blocked: markup context “Matching lesson markup is not supplied; this fragment uses a generic HTML scaffold.”. Provide inline styles and scripts, embedded images or the missing HTML context. External requests and browser dialogs stay blocked.

function safeSetItem(key, value) {
  try {
    localStorage.setItem(key, value);
    return true;
  } catch (e) {
    if (e.name === "QuotaExceededError") {
      console.error("Storage quota exceeded");
    } else {
      console.error("Error saving to localStorage:", e);
    }
    return false;
  }
}

function safeGetItem(key, defaultValue) {
  try {
    var value = localStorage.getItem(key);
    return value !== null ? value : defaultValue;
  } catch (e) {
    console.error("Error reading from localStorage:", e);
    return defaultValue;
  }
}

🔒 Security Notes

  • Web Storage is accessible via JavaScript - vulnerable to XSS attacks
  • Data is stored unencrypted in plain text
  • Never store sensitive information like passwords or credit cards
  • Data persists across sessions (localStorage) - consider privacy implications

Test Your Knowledge

5 practice questions are available. Choose Start practice to try them.