DOM Storage – JavaScript Web Storage

file1

Level: intermediate

There is no problem with Web apps with server-side back end code, where we can for example store data in MySQL or simply – in files. Thanks to Web storage / DOM storage, our modern web application can store the data itself, and we will handle them in JavaScript.

JavaScript Web Storage

It is a part of the HTML5 specification. We understand web storage as methods and protocols for storing data locally – “in the browser”.

It’s similar to the mechanism of cookies; however, web storage provides more possibilities, including greater capacity available for our data (storage).

Cookies are available both for front (client-side) and server-side (e.g. PHP). Web storage is reserved only for client-side scripting.

Using Web Storage – JavaScript

We have local storage and session storage. The browsers with JavaScript Web storage have the sessionStorage and localStorage variables declared globally.

For sessionStorage the data are set for the duration of the session.

Example – set and get data from sessionStorage:

// set
sessionStorage.setItem('key', 'JavaScript Web Storage!');

// get
alert(sessionStorage.getItem('key'));

For localStorage it looks the same.

Example – set and get data from localStorage:

// set
localStorage.setItem('test', 'Local storage!');

// get
alert(localStorage.getItem('test'));

Simple and easy.

The number of items stored in localStorage we can check with localStorage.length. Thus, we can simply refer to all stored data.

Example:

var output = "DATA:\n-----\n";
if (window.localStorage) {
  if (localStorage.length) {
    for (var i = 0; i < localStorage.length; i++) {
      output += localStorage.key(i) + ': ' 
        + localStorage.getItem(localStorage.key(i)) + '\n';
    }
  }
}
console.log(output);

Sample result:


DATA:
—–
test: Local storage!
test2: Foo bar

Sample code on GitHub:

https://github.com/dominik-w/js_html5_com/blob/master/web-storage-demo.html

To determine if the browser supports localStorage we can also use the Modernizr library:

if (Modernizr.localstorage) {
  // ...
}

Data types

In the web storage we store the key-value pairs. Both keys and values are strings (type). We can keep the data as JSON:

localStorage.setItem('key', JSON.stringify({name: 'myval'}));
alert(JSON.parse(localStorage.getItem('key')).name);

The next examples is a simple counter of clicks:

if (localStorage.cnt) {
    localStorage.cnt = Number(localStorage.cnt) + 1;
} else {
    localStorage.cnt = 1;
}
document.getElementById("result").innerHTML = "You clicked " +
  localStorage.cnt + " time(s)";

The simple and efficient mechanism.

Properties and methods of JavaScript DOM Storage

The DOM Storage object only provides several methods and properties.

Methods

– getItem(key) – returns the content stored under the key, or null if no value for such a key

– setItem(key, value) – writes the string value for a given key; if such a key exists, the previous value will be replaced by the new value

– removeItem(key) – removes the value stored under the key

– key(index) – returns the key name for the index

– clear() – removes all the data from the DOM Storage for current domain

Properties

length – read-only property; returns the number of elements in DOM storage


Resources

– MDN

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage

– description in HTML5 handbook

http://diveintohtml5.info/storage.html

– tutorial: creating address book based on JavaScript Web Storage

http://www.diveintojavascript.com/tutorials/web-storage-tutorial-creating-an-address-book-application

Summary

In case of Web Storage we received a small extension which is a huge convenience in modern Web applications programming.

localStorage.setItem(‘thanks’, ‘Thank you for your attention’);

Web and Mobile Software Developer, with years of experience. My biggest passions are programming, new technologies, e-commerce, as well sports, cars, and of course my family.

Facebook Twitter LinkedIn Google+ Skype Xing 

Share: Share on Facebook0Tweet about this on TwitterShare on Google+1Share on LinkedIn3Share on Tumblr0Digg thisEmail this to someonePin on Pinterest1
You can leave a response, or trackback from your own site.