Window: sessionStorage property - Web APIs | MDN (original) (raw)

The read-only sessionStorage property accesses a session Storage object for the currentorigin. sessionStorage is similar tolocalStorage; the difference is that while data in localStorage doesn't expire, data in sessionStorage is cleared when the page session ends.

Data stored in sessionStorage is specific to the protocol of the page. In particular, data stored by a script on a site accessed with HTTP (e.g., http://example.com/) is put in a different sessionStorage object from the same site accessed with HTTPS (e.g., https://example.com/).

The keys and the values are always in the UTF-16 string format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings.

Value

A Storage object which can be used to access the current origin's session storage space.

Exceptions

SecurityError

Thrown in one of the following cases:

Note that if the user blocks cookies, browsers will probably interpret this as an instruction to prevent the page from persisting data.

Examples

Basic usage

// Save data to sessionStorage
sessionStorage.setItem("key", "value");

// Get saved data from sessionStorage
let data = sessionStorage.getItem("key");

// Remove saved data from sessionStorage
sessionStorage.removeItem("key");

// Remove all saved data from sessionStorage
sessionStorage.clear();

Saving text between refreshes

The following example autosaves the contents of a text field, and if the browser is refreshed, restores the text field content so that no writing is lost.

// Get the text field that we're going to track
let field = document.getElementById("field");

// See if we have an autosave value
// (this will only happen if the page is accidentally refreshed)
if (sessionStorage.getItem("autosave")) {
  // Restore the contents of the text field
  field.value = sessionStorage.getItem("autosave");
}

// Listen for changes in the text field
field.addEventListener("change", () => {
  // And save the results into the session storage object
  sessionStorage.setItem("autosave", field.value);
});

Specifications

Specification
HTML Standard # dom-sessionstorage-dev

Browser compatibility

BCD tables only load in the browser

See also