SessionStorage property in JavaScript

The read-only sessionStorage property accesses a session Storage object for the current originsessionStorage 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.

// 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();

This is a good candidate for saving text between refreshes. Here is an example;

// 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);
});

Reference

https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

FavoriteLoadingAdd to favorites
Spread the love

Author: Shahzad Khan

Software developer / Architect