Tutorials JavaScript HTML5 Storage using JavaScript localStorage and sessionStorage

HTML5 Storage using JavaScript localStorage and sessionStorage

Hello everybody and welcome back to PHP Trainee. Today you will learn how to pass data between pages using JavaScript.

JavaScript was originally created for the purpose of interactivity on websites. First rule of JavaScript they taught me in school was to make sure the website works fine without JavaScript. It was never intended to hold content. However, there are no absolutes in life and sometimes you need to manipulate data with JavaScript.

Pre-HTML5

One of the biggest limitations of JavaScript was that browsers restarted all JavaScript on every HTTP request. It was impossible to store content client-side. Previously, there were only two ways for JavaScript to send data to along with that reload:

  • Creating cookies: document.cookie
  • Pass it along the URL: http://www.example.com/about.html#foobar

The problem with JavaScript cookies is that it returns everything as one long string so you have to you have to do a regex parse to retrieve the data. The problems with passing it through the URL are numerious: SEO, limited length, looks ugly, and parsing errors with spaces. You could also fake page loads with AJAX and continue to use JavaScript, but that's something else entirely.

Browser Storage

JavaScript now has the ability to store data in the browser. They work like cookies and sessions and persist between pages. We can use localStorage and sessionStorage to hold data. sessionStorage gets deleted when the browser is closed while localStorage keeps its data even after the browser closes. localStorage is also synced on the browser; multiple tabs share the same localStorage. sessionStorage only works on that specific tab. Storage works in Internet Explorer 8+ and all other modern browsers.

Assign key-pair data sets

// Syntax: localStorage.setItem(key,value);
localStorage.setItem('fruit', 'apple');

// Syntax: sessionStorage.setItem(key,value);
sessionStorage.setItem('vegetable', 'cabbage');

Retrieve key-pair data sets

// Syntax: localStorage.getItem(key);
var fruit = localStorage.getItem('fruit');

// Syntax: sessionStorage.getItem(key);
var veggie = sessionStorage.getItem('vegetable');

Delete data from storage

You can use removeItem(key) to remove a specific item or clear() to delete everything in the browser storage.

// Syntax: localStorage.removeItem(key);
localStorage.removeItem('fruit');

// Syntax: sessionStorage.removeItem.getItem(key);
sessionStorage.removeItem('vegetable');

// No variables, complete purge
localStorage.clear();
sessionStorage.clear();

Storage Events

The storage event fires whenever a storage object is changed on another tab using setItem, removeItem, or clear.

Note: This storage event only fires on other tabs; you will need at least two tabs open of the same site for this event to trigger. It is usually only useful with localStorage as sessionStorage is not available across different windows. It also requires an actual change; it doesn't fire if you clear or remove what doesn't exist, or set the value to the same thing as before. The storage event returns key, oldValue, newValue, url and storageArea.

PropertyReturnDescription
keystringThe key of the item changed.
oldValuestringThe data before being changed.
newValuestringThe new data being set.
urlstringThe URL of the webpage that initiated the change.
storageAreaobjectThe storage object (sessionStorage or localStorage) that was affected
window.addEventListener('storage', function(e) {  
  var k = e.key;
  var o = e.oldValue;
  var n = e.newValue;
  var u = e.url;
  var l = e.storageArea;
  var t = u +' just changed '+ k +' from '+ o +' to '+ n;
  
  alert(t);
});

Loops

You can use length to get the number of items in storage. You can use key(index) to get the key. You can use the key to grab the values. Combine these facts and you can easily make a loop to get everything in storage.

var len = localStorage.length;
for (var i = 0; i < len; i++) {
  var k = localStorage.key(i);
  var v = localStorage.getItem(k);
  
  console.log(k +': '+ v);
}

Storage Limitations

The key and value can only hold strings. Anything that is not a string will be converted to a string. JavaScript objects will be converted to "[object Object]". Hopefully in the future, browsers will support actual objects as values.

Demo

Demo Link (Open this in multiple tabs to see the storage event trigger on localStorage changes)

Posted by on . Category: JavaScript


Comments

No comments posted yet

You need to register or login to post new comments.