Use of sessionstorage and localStorage - step-by-step

Posted by Byron on Thu, 05 Dec 2019 05:38:09 +0100

Use of sessionStorge

The sessionStorage property allows you to access a session Storage object. It is similar to localStorage, except that the data stored in localStorage has no expiration time setting, and the data stored in sessionStorage will be cleared at the end of the page session. The page session is maintained while the browser is open, and the original page session is maintained when the page is reloaded or restored. When a page is opened in a new tag or window, a new session will be initialized in the top-level browsing context, which is different from the way session cookies operate

grammar

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

// Get data from sessionStorage
var data = sessionStorage.getItem('key');

// Delete saved data from sessionStorage
sessionStorage.removeItem('key');

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

Example

// Get text input box
var field = document.getElementById("field");
 
// Check whether autosave key exists
// (this will exist when the page is accidentally refreshed)
if (sessionStorage.getItem("autosave")) {
  // Restore the contents of the text input box
  field.value = sessionStorage.getItem("autosave");
}
 
// Listen for change event of text input box
field.addEventListener("change", function() {
  // Save the results to the sessionStorage object
  sessionStorage.setItem("autosave", field.value);
});

Use of localStorage

Read only localStorage allows you to access a Document's remote (origin) object Storage; the data is stored as a cross browser session. localStorage is similar to sessionStorage. The difference is that data stored in localStorage is indefinite, and when the page session ends - that is, when the page is closed, data stored in sessionStorage is cleared

grammar

//Set up
localStorage.setItem('myCat', 'Tom')
//read
let cat = localStorage.getItem('myCat');
//remove
localStorage.removeItem('myCat');
// Remove all
localStorage.clear();

Example

function setStyles() {
  var currentColor = localStorage.getItem('bgcolor');
  var currentFont = localStorage.getItem('font');
  var currentImage = localStorage.getItem('image');

  document.getElementById('bgcolor').value = currentColor;
  document.getElementById('font').value = currentFont;
  document.getElementById('image').value = currentImage;

  htmlElem.style.backgroundColor = '#' + currentColor;
  pElem.style.fontFamily = currentFont;
  imgElem.setAttribute('src', currentImage);
}

Topics: Javascript Session mycat