HTML Session Storage

Beginner
12 min read
Updated: Nov 2026
5 examples
Web Storage API

Definition and Usage

Session Storage is the browser’s sessionStorage object from the Web Storage API. From a <script> in your HTML page you save string key-value pairs for the current tab. Data survives reloads of that HTML document and is cleared when the tab or window closes.

How does a page session work?

Loading a document in a tab creates a page session for that tab. The main page and same-origin iframes share that tab’s storage. A new tab gets a new session (unlike session cookies). Closing the tab ends the session and deletes the data.

How is this useful in HTML pages?

Autosave draft text in an <input> or <textarea> across an accidental refresh, remember a wizard step for this visit only, or keep a temporary cart for one checkout tab—without sending data to a server.

When should you use sessionStorage vs localStorage?

Use sessionStorage for tab-scoped, temporary state. Use localStorage for settings that should persist across visits and be shared by every tab of the same origin.

Strings only.

Keys and values are strings. Store objects with JSON.stringify / JSON.parse.

Not a vault.

Same-origin scripts can read sessionStorage. Never store passwords or payment secrets there.

Opener note.

A page opened with window.open may start with a copy of the opener’s sessionStorage, but the two stores stay separate afterward.

HTML / Script Syntax

Call methods on sessionStorage from a script in your HTML document:

JS
sessionStorage.setItem("key", "value");
var data = sessionStorage.getItem("key");   // string or null
sessionStorage.removeItem("key");
sessionStorage.clear();                     // remove all keys for this tab
sessionStorage.key(0);                      // name of key at index
sessionStorage.length;                      // number of keys
HTML
<input id="field" type="text">
<script>
  var field = document.getElementById("field");
  if (sessionStorage.getItem("autosave")) {
    field.value = sessionStorage.getItem("autosave");
  }
  field.addEventListener("change", function () {
    sessionStorage.setItem("autosave", field.value);
  });
</script>

Core HTML Concepts

How session storage fits into HTML pages and browser tabs:

ConceptMeaning
sessionStoragePer-origin, per-tab Storage object on window
Page sessionLasts while the tab is open; survives HTML reloads
setItem / getItemWrite and read string values
removeItem / clearDelete one key or all keys in this tab
key / lengthInspect stored keys for debugging
Same originScheme + host + port must match to share storage
New tabStarts a new empty sessionStorage (separate from other tabs)
localStoragePersistent, shared across tabs of the same origin

sessionStorage vs localStorage

sessionStoragelocalStorage
ScopeOne tab (top-level browsing context)All tabs of the origin
LifetimeUntil tab/window closesUntil cleared by script or user
Survives reload?YesYes
Best forDrafts, wizards, one-visit stateTheme, prefs, lasting data

How to Use Session Storage in HTML

Wire storage to real form controls and page load.

  1. Add HTML controls (input, textarea, buttons) with ids.
  2. On save or change, call sessionStorage.setItem(key, value).
  3. On page load (script at end of body or DOMContentLoaded), getItem and restore into the control.
  4. Use removeItem when a step is finished, or clear to wipe the tab session.
  5. Serialize objects with JSON before storing; parse carefully when reading.
GoalPattern
Save a stringsessionStorage.setItem("name", "Alex")
Restore after reloadinput.value = sessionStorage.getItem("name") || ""
Store an objectsetItem("cart", JSON.stringify(obj))
Forget one keysessionStorage.removeItem("name")
Reset the tab storesessionStorage.clear()

Live Preview

Save a value into this tab’s sessionStorage, then reload the page—the value stays until you clear it or close the tab.

Uses key ctf-ss-demo in this tab only. Try Save, then refresh the tutorial page.

sessionStorage status

No value saved yet.

sessionStorage.getItem("ctf-ss-demo") → null

HTML Examples

Five patterns: save/read strings, JSON objects, remove keys, list keys, and a full HTML page demo.

Example 1 — Save and Read a String

JS
sessionStorage.setItem("username", "JohnDoe");
var name = sessionStorage.getItem("username");
console.log(name); // JohnDoe
Try It Yourself

How It Works

  1. setItem writes (or overwrites) a key for this tab.
  2. getItem returns the string, or null if missing.
  3. Same tab reload keeps the value; a new tab does not see it.
  4. Try It wires the API to HTML input buttons.

Example 2 — Store an Object with JSON

JS
var cart = { items: 2, total: 19.99 };
sessionStorage.setItem("cart", JSON.stringify(cart));

var loaded = JSON.parse(sessionStorage.getItem("cart"));
console.log(loaded.total); // 19.99
Try It Yourself

How It Works

  1. stringify turns the object into a string Web Storage accepts.
  2. parse rebuilds the object after getItem.
  3. Guard parse with try/catch if data might be corrupt.
  4. Keep payloads small — browsers often cap storage near 5 MB per origin.

Example 3 — Remove One Key

JS
sessionStorage.setItem("temp", "draft");
sessionStorage.removeItem("temp");
console.log(sessionStorage.getItem("temp")); // null
Try It Yourself

How It Works

  1. removeItem deletes one key; missing keys do not throw.
  2. clear() wipes every key in this tab’s sessionStorage.
  3. Closing the tab also clears everything for that session.
  4. Use remove when a wizard step finishes so stale drafts do not linger.

Example 4 — List All Keys

JS
for (var i = 0; i < sessionStorage.length; i++) {
  var key = sessionStorage.key(i);
  console.log(key, sessionStorage.getItem(key));
}
Try It Yourself

How It Works

  1. length is how many keys this tab currently stores.
  2. key(i) returns the key name at that index.
  3. Debug tip — list keys when an HTML form restore looks wrong.
  4. Order of keys is not guaranteed across browsers.

Example 5 — Full HTML Page (Save / Load)

Connect sessionStorage to HTML inputs so a name survives reload in this tab:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Session Storage Example</title>
</head>
<body>
  <h1>Session Storage Example</h1>
  <input type="text" id="input" placeholder="Enter your name">
  <button type="button" id="save">Save</button>
  <button type="button" id="load">Load</button>
  <p id="result"></p>

  <script>
    document.getElementById("save").onclick = function () {
      sessionStorage.setItem("userName", document.getElementById("input").value);
    };

    document.getElementById("load").onclick = function () {
      var userName = sessionStorage.getItem("userName");
      document.getElementById("result").textContent =
        userName ? "Hello, " + userName : "No name saved";
    };

    var saved = sessionStorage.getItem("userName");
    if (saved) {
      document.getElementById("input").value = saved;
      document.getElementById("result").textContent = "Welcome back, " + saved;
    }
  </script>
</body>
</html>
Try It Yourself

How It Works

  1. HTML provides the UI; the script talks to sessionStorage.
  2. Save writes the input value under userName.
  3. Auto-restore on load fills the field after a refresh.
  4. Close the tab and reopen—the saved name is gone.

Edge Cases & Pitfalls

Most surprises come from tab scope, string-only values, or blocked storage.

tabs

Expecting data in a new tab

Opening the same HTML URL in another tab starts a new sessionStorage. Duplicate data only if you copy it yourself (or use localStorage).

types

Storing numbers/objects raw

Non-strings are coerced. Prefer explicit String(…) or JSON so you do not get "[object Object]".

null

Forgetting null checks

getItem returns null when missing. Guard before writing into HTML inputs.

quota

QuotaExceededError

Very large strings can throw. Catch errors around setItem for big drafts.

file

file: / blocked cookies

Some environments throw SecurityError. Test over http(s). Privacy modes that block site data also block storage.

secrets

Sensitive data in HTML apps

XSS can read sessionStorage. Keep tokens and PII on the server with proper auth cookies when possible.

Browser Support

sessionStorage is part of the Web Storage API and is supported in all modern browsers.

✓ Baseline · Widely available

sessionStorage in HTML pages

Per-tab Web Storage works across current browsers for same-origin HTML documents.

100% sessionStorage support
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
Web Storage sessionStorage Universal

Bottom line: Use sessionStorage for tab-scoped drafts—support is widespread; watch privacy settings and file: origins.

Key Takeaways

  • Per tab: sessionStorage is scoped to one browsing context, not every tab.
  • Survives reload of the HTML page; clears when the tab closes.
  • API: setItem, getItem, removeItem, clear.
  • Wire to HTML inputs so drafts restore after refresh.

One line: From your HTML page’s script, use sessionStorage for temporary, tab-only key-value data that outlives a refresh.

Frequently Asked Questions

sessionStorage is a Web Storage API on the window object. From a script in your HTML page you store string key-value pairs for the current browser tab. Data survives reloads of that page but is cleared when the tab or window closes.
localStorage is shared across tabs of the same origin and lasts until cleared. sessionStorage is partitioned by origin and by tab: each tab has its own store for the page session.
Yes. Reloading the same tab keeps sessionStorage. Opening the same HTML URL in a new tab starts a new, empty session for that tab.
On input or change events, call sessionStorage.setItem(key, value). On page load, read with getItem and write the value back into the form control so users do not lose draft text.
Only strings are stored. Use JSON.stringify before setItem and JSON.parse after getItem when you need objects.
Some origins (for example file: pages) or browser privacy settings that block site data can prevent Web Storage. Prefer testing over http(s) and avoid storing secrets—storage is readable by same-origin scripts.

Practice in the editor

Open the full save/load HTML demo and reload the tab to see sessionStorage persist.

Open Try It editor →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful