/    /  Javascript Storage Handling

Javascript Storage Handling

 

Storage objects are simply known as key-value stores, similar to objects. But they stay intact through page loads. The keys and the values are always strings. We can access these values like an object, or with the Storage.getItem() and Storage.setItem() js methods. These three lines all set the (same) color setting entry:

 

localStorage.colorSetting = '#a4509b';
localStorage['colorSetting'] = '#a4509b';
localStorage.setItem('colorSetting', '#a4509b');

 

Two mechanisms within Web Storage:

 

1. sessionStorage maintains a separate storage area for every given origin and that is available for the time duration of the page session.

2. localStorage does the same thing but the main difference persisted even when the browser is closed and reopened.

These two storages are providing via the Window.sessionStorage and Window.localStorage properties. Invoking one of these will generate an instance of the Storage object(sessionStorage or localStorage), through which data items can be set, retrieved, and removed. A different Storage object is providing for the sessionStorage and localStorage for each origin they function and are controlled separately.

 

LocalStorage is both supported and available:

 

function storageAvailable(type) {
var storage;
try {
storage = window[type];
var x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch(e) {
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
(storage && storage.length !== 0);
}
}

 

And here is how you would use it:

 

if (storageAvailable('localStorage')) {
// Yippee! We can use localStorage awesomeness
}
else {
// Too bad, no localStorage for us
}

 

Getting values from storage:

 

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

 

Setting values in storage:

 

function populateStorage() {
  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);
  localStorage.setItem('font', document.getElementById('font').value);
  localStorage.setItem('image', document.getElementById('image').value);

  setStyles();
}