Session Storage: Keep a Draft During a Tab Session

Save JavaScript tab-session data and read browser storage values across reloads.

A form draft can disappear on reload when its value exists only in a JavaScript variable. Browser storage for a page session can retain a small draft in the same tab across reloads. The example below uses JavaScript to save, read, and remove that session data, while reporting when storage is unavailable.

Session Storage JavaScript Example: Save a Draft

Save this file as index.html and serve it from a local HTTP server, such as python -m http.server in its directory. Open the server’s address in a browser. Enter a note, save it, reload, and then remove it. The message shows whether each operation succeeded.

<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Tab draft</title></head>
<body>
  <label for="draft">Draft note</label>
  <textarea id="draft"></textarea>
  <button id="save" type="button">Save draft</button>
  <button id="remove" type="button">Remove draft</button>
  <p id="status" role="status"></p>
  <script>
    const key = "draftNote";
    const draft = document.querySelector("#draft");
    const status = document.querySelector("#status");

    function restore() {
      try {
        const saved = sessionStorage.getItem(key);
        draft.value = saved === null ? "" : saved;
        status.textContent = saved === null ? "No saved draft." : "Draft restored.";
      } catch (error) {
        status.textContent = "Storage unavailable; the draft is only in this page.";
      }
    }

    document.querySelector("#save").addEventListener("click", () => {
      try {
        sessionStorage.setItem(key, draft.value);
        status.textContent = "Draft saved for this tab.";
      } catch (error) {
        status.textContent = "Could not save; keep a copy elsewhere.";
      }
    });

    document.querySelector("#remove").addEventListener("click", () => {
      try {
        sessionStorage.removeItem(key);
        draft.value = "";
        status.textContent = "Draft removed.";
      } catch (error) {
        status.textContent = "Could not remove the saved draft.";
      }
    });
    restore();
  </script>
</body>
</html>

The JavaScript sessionStorage interface stores the textarea’s string under draftNote. getItem() returns null when the key is absent; an empty string is a saved value, so the example tests for null explicitly. removeItem() deletes only this key. Calling clear() would remove every key in the same storage area, including keys used by other parts of the application.

Try the sequence in DevTools as well: open the storage panel, select the page’s origin under the session-storage section, and inspect draftNote. Edit the note and save again to see the value change. After removal, the key disappears. If a save fails, the textarea still holds its current text until the page is reloaded or closed, giving the reader a chance to copy it.

Strings, objects, and missing values

Storage keys and values are strings. The example stores a string directly; calling setItem on a plain object does not preserve its fields. Serialize a small object to JSON and parse it when reading:

try {
  const preferences = { theme: "dark", page: 2 };
  sessionStorage.setItem("preferences", JSON.stringify(preferences));
  const raw = sessionStorage.getItem("preferences");
  const restored = raw === null ? null : JSON.parse(raw);
  console.log(restored);
} catch (error) {
  console.error("Could not store or read preferences:", error);
}

This JavaScript example using tab storage can fail during access, writing, or parsing. A stored value may be malformed or left over from an older version of an application. Validate the parsed object’s properties before using them, and decide whether to discard an invalid value or migrate it. JSON is useful for ordinary data, but it does not automatically preserve every JavaScript type or a cyclic object graph.

Understand the origin and tab boundary

An origin is the combination of scheme, host, and port. Pages of the same origin in the same tab can use the same session storage area; a different origin gets a different area. Reloading the page normally retains its values. Closing the tab or window ends that page session, so this is a temporary convenience rather than durable backup. Browser session restoration can affect what you observe when restoring a closed browsing session.

A newly opened tab normally has its own area. There is a nuance: if a new page has an opener, its initial storage can be a copy of the opener’s area. The two areas then change independently. Opening the URL in an independently created tab is a useful comparison: it starts a separate page session instead of acting as a live view of the original. Browser controls for duplicating or restoring a tab can have their own behavior, so test the workflow your application asks users to follow. Removing the opener relationship, for example with an appropriate noopener link, avoids that initial copy. To verify, open a same-origin page with an opener, inspect the initial value, change it in one tab, and observe that the other tab does not follow the change.

For session storage javascript code, this scope matters when a user opens a second tab and expects a draft to stay synchronized. The two tabs are not a shared live store. Use an application design with explicit synchronization when that behavior is required, and choose a persistence mechanism suited to the expected lifetime.

Distinguish browser data from a server session

Can JavaScript get a session variable from the server directly? Not merely by reading browser storage: server session variables live on the server. The application must expose an authorized endpoint or embed an appropriate value in the page for client code to read. A session cookie may identify the server-side session, but the stored server values are not automatically available to scripts.

Can JavaScript set a session variable on the server by calling setItem()? No. To set a session variable in JavaScript through the server, send an authorized request to an endpoint that validates the input and updates its own session. The browser’s storage and the server’s state have separate lifetimes and access rules. For JavaScript, getting a server session value requires an explicit response; setting a server session value requires server-side handling.

Values in browser storage can be read or changed by scripts running in the same origin. Do not treat them as trusted authorization state or a secure place for secrets. The server should verify permissions independently, and the page should validate any stored data before using it. Storage operations are synchronous, so keep this space for modest amounts of data rather than large or frequent writes. For example, saving a few form fields when the user presses a button is easier to reason about than rewriting a large document on every keystroke. If automatic saving is required, consider a short debounce and show the user whether the latest edit was actually saved. An in-memory fallback can keep the page usable, but it cannot restore a draft after a reload.

Diagnose a failed save

The most likely surprise is a draft that disappears after reload because the write failed or the page is using a different origin. Look for the example’s failure message and inspect the console and DevTools storage panel. Check the scheme, host, and port, confirm the draftNote key exists, and retry from the same tab after resolving the cause. A SecurityError can indicate an invalid origin or blocked persistence; a quota error can mean the storage limit was reached. Serve the page over HTTP, review browser storage settings, or remove unneeded data as appropriate, then save and reload again.