The sessionStorage property accesses a session Storage object for the current origin. sessionStorage is similar to localStorage; the difference is that while data in localStorage doesn't expire, data in sessionStorage is cleared when the page session ends.
- A page session lasts as long as the browser is open, and survives over page reloads and restores.
- Opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.
- Opening multiple tabs/windows with the same URL creates
sessionStoragefor each tab/window. - Closing a tab/window ends the session and clears objects in
sessionStorage.
Data stored in sessionStorage is specific to the protocol of the page. In other words, http://example.com will have separate storage than https://example.com.
Syntax
// 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();
Value
A Storage object.
Example
The following snippet accesses the current origin's session Storage object and adds data to it with Storage.setItem().
sessionStorage.setItem('myCat', 'Tom');
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", function() {
// And save the results into the session storage object
sessionStorage.setItem("autosave", field.value);
});
Note: Please refer to the Using the Web Storage API article for a full example.
Specifications
| Specification | Status | Comment |
|---|---|---|
| HTML Living Standard The definition of 'sessionStorage' in that specification. |
Living Standard |
Browser compatibility
| Desktop | Mobile | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
sessionStorage | Chrome Full support 5 | Edge Full support 12 | Firefox Full support 2 | IE Full support 8 | Opera Full support 10.5 | Safari Full support 4 | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support Yes | Opera Android Full support 11 | Safari iOS Full support 3.2 | Samsung Internet Android Full support Yes |
Legend
- Full support
- Full support