By Ashwin Date on Tuesday, 25 November 2014
Category: Mobile Development

LocalStorage Rocks…!

HTML5 has introduced one of the very useful concept called Local Storage. Local storage can be used in applications that need to save some user data and references even after application restarts. In this article we would be talking about the methods of using the local storage.

Overview

Local Storage API gives access to simple key-value data store that can be used to store data on client side. Saving data on client side helps to speed up performance of app and reduce number of database queries that are needed on server. This frees up valuable server resources and can lead to reduced infrastructure costs.

Before the introduction of LocalStorage, developers that wanted to store data on the client side would need to use browser cookies. While this approach did work it had some problems. 

The Local Storage can be used across 

Checking Browser Support

LocalStorage is a new technology and therefore it is important to test for browser support and consider fall backs for browsers that do not support the API. The below javascript code shows how to check if a browser supports the LocalStorage API. Note the lowercase ‘l’ in localStorage.

if (localStorage) { 
    // LocalStorage is supported! 
} 
else { 
    // No support. Use a fallback such as browser cookies or store on the server. 
} 

If the browser does not support LocalStorage you could fallback to using browser cookies or just send the data to be stored on the server.

Storing Data

To store data use the setItem() function. This function takes two parameters, the itemkey and value.

localStorage.setItem('name', 'Matt West'); 

There are multiple ways to interact with the localStorage interface. You can also treat the localStorage interface like a JavaScript object or array. Below all examples will store data.

// Functions 
localStorage.setItem('name', 'Matt West'); 

// Object 
localStorage.name = 'Matt West'; 

// Array 
localStorage['name'] = 'Matt West'; 

Implementation

Lets take a look at a simple use of LocalStorage in a website. The code below is markup for a contact form. When the user submits the form we are going to save their name so that we can use it later to show them a personalized message.

<form id="contactForm" action="contact.php" method="POST">
   <div class="field"> 
      <label for="name">Name</label>
      <input type="text" name="name" id="name">
   </div>
   <div class="field"> 
      <label for="email">Email</label> 
      <input type="email" name="email" id="email">
   </div>
   <div class="field">
      <label for="message">Message</label>
      <textarea name="message" id="message"></textarea> 
   </div>
   <div class="field"> 
      <input type="submit" value="send">
   </div>
</form> 

The below javascript code shows how you could intercept the form submission and save the user’s name.

Retrieving Data

To retrieve data use the getItem() function. This takes a single parameter; the key that you used when storing data.

var name = localStorage.getItem('name'); 

Building on our previous contact form example, in the code below we retrieve the user’s name from the datastore and then update an element on the page with the text Hello {name}!.

window.onload = function() {
    // Check for LocalStorage support.
    if (localStorage) {
        // Add an event listener for form submissions
        document.getElementById('contactForm').addEventListener('submit', function() {
            // Get the value of the name field
            var name = document.getElementById('name').value;
            // Save the name in localStorage
            localStorage.setItem('name', name);
        });
    }
} 

The if statement is used to make sure that there is a name stored in the database. If we didn’t do this our program might say Hello undefined!. If you attempt to access data that does not exist the localStorage, it will return either null or undefined depending on how you tried to access the data.

Removing Data

To remove an item from the Local Storage use the removeItem() function. This function takes the key of the item that you wish to delete.

localStorage.removeItem('name'); 

Clearing the Datastore

If you want to delete all of the data in the Local Storage you can use the clear() function.

localStorage.clear(); 

Retrieving Keys

The localStorage interface also includes a function called key(), that can be used to retrieve the key of a data item using the index (numerical position) of the item in the data store. The below javascript code shows how to use this function to output the keys for each of the items in the Local Storage. The length property tells you how many items are in the Local Storage.

for (var i = 0; i < localStorage.length; i++) {
    console.log(localStorage.key(i))
}; 

Sandboxing and Storage Limits

The data that you add to the LocalStorage is sandboxed to your websites domain name. This means that your web application cannot see the data stored by any other applications and those applications cannot see the data stored by yours. This is an important security measure.

Sub-domains (i.e. a.example.com, b.example.com, c.example.com) are treated as separate domains and are therefore given their own data store.

There is a limit on how much data you can put in LocalStorage. This limit is set by browser vendors and therefore varies between browsers. To be safe, you should assume that your web application has only 2.5 MB of storage space. This should be more than enough space as LocalStorage is only designed to hold basic key-value data. If you find yourself needing more space you might want to reconsider whether LocalStorage is the best storage technology for your application.

SessionStorage

Data stored in LocalStorage is persistent. This means that if you store some data, close your browser and then open up your application again, all of the data will still be retrievable. However you may only want to store some data for the duration of a user session. In this case you can use the sessionStorage interface. This has all of the same functions that localStorage does but the data you save will automatically be wiped when the user closes the browser tab.

// Storing Data
sessionStorage.setItem('name', 'Matt West');

// Retrieving Data
var name = sessionStorage.getItem('name');

// Deleting Data
sessionStorage.removeItem('name');

// Retrieving an Item Key
sessionStorage.key(n);

// Clearing the Datastore
sessionStorage.clear(); 

Thoughts on LocalStorage

The LocalStorage API allows developers to make considerable advances in the performance of their web applications. Looking past this initial advantage, LocalStorage also provides a data store for offline applications (assuming that a technology like AppCache is being used to make the other application resources available). 

I am especially interested about the potential applications that LocalStorage has for HTML5 mobile applications. Mobile devices are much more likely to be without an internet connection and therefore without access to traditional server-based datastores.

Are you using LocalStorage in any interesting ways in your projects? Let us know in the comments below.

Leave Comments