PMG Digital Made for Humans

Using HTML5's LocalStorage Like A Boss

6 MINUTE READ | April 19, 2012

Using HTML5's LocalStorage Like A Boss

Author's headshot

Chris Alvares, Head of Technology

Chris Alvares has written this article. More details coming soon.

The problem with using web browser cookies is they are passed from server to browser back to server, and while this is good way to send relevant persistent data to the server, it isn’t good for stuff like saving input field values, especially if those values can change depending on the type of page you are on, you are going to end up with a ton of useless data being passed with every request. W3C took to try to solve this problem. The first attempt by the W3C and the browser makers tried to implement was a SQLite type database. They called the original specification WebDB. However, after its inception, the developers at Mozilla did not want to implement it. They complained, saying that developers do not want to use SQL in the browser (You can read the conversation here). When I first read about this, I was shocked, and thought that Mozilla developers were just being lazy. That changed when I first started using HTML5’s new LocalStorage feature. It is exactly what the web needed. No longer tied down from having to have SQL queries, the key-value storage engine was perfect for 99% of web applications. Here is one way to use LocalStorage like a boss.

In this example, we will be creating two javascript methods to turn any pages input fields to automatically fill in previous values when the user hits the “Submit” button.

Lets start out with a basic HTML Shell, and also include jQuery into the mix to make things move a bit faster.

<!DOCTYPE html>

<html>

<head>

<title>Local Storage Like a Boss</title>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

</head>

<body>

<form>

<table>

<tr>First Name: </tr><td><input type="text" name="fname" id="fname"></input></td>

<tr>Last Name: </tr><td><input type="text" name="lname" id="lname"></input></td>

<tr><td colspan="2" style="text-align:right"><button onclick="saveToLocalStorage(); return false;">Save</button></td></tr>

</table>

</form>

</body>

</html>

As you can see from the HTML shell we built, the has an onclick event titled saveToLocalStorage().

function saveToLocalStorage()

{

if(window.localStorage != null)

{

//use the URL of the page as our "key"

var url = location.href;

if(url.indexOf("#") != -1)

url = url.substr(0,url.indexOf('#'));

var key = "inputs-" + url;

var values = {};

jQuery("form input").each(function(){

values[jQuery(this).attr("name")] = jQuery(this).val();

});

try

{

localStorage.setItem(key, JSON.stringify(values));

}

catch(e)

{

localStorage.removeItem(key);

}

}

}

Lets walk this line by line.

The first thing we need to do is check if LocalStorage is supported, and the way we do that is with the line:

if(window.localStorage != null) {

This will make all browsers that do not support it act in a normal behavior. The next thing we have to do is creating a key value pair for our input fields. Now, there are two ways to do this, use seperate key values pairs for each input field, or, the way I like to do it, have one key-value pair where they key is the URL of the webpage, and the value is a JSON string with each of the key value pairs. This makes it faster to retrieve key value pairs from LocalStorage, and it is easy to iterate through the JSON data to fill in all the input fields.

//use the URL of the page as our "key"

var url = location.href;

if(url.indexOf("#") != -1)

url = url.substr(0,url.indexOf('#'));

var key = "inputs-" + url;

//use a dictionary as the keys

var values = {};

//get all of the input fields on the page, and call them by their names, if they have a name

jQuery("form input").each(function(){

if(jQuery(this).attr("name") != "")

values[jQuery(this).attr("name")] = jQuery(this).val();

});

Finally, the LocalStorage part comes. To store something in the LocalStorage, it is as easy as calling the window.localStorage class and the setItem method.

try

{

localStorage.setItem(key, JSON.stringify(values));

}

catch(e)

{

localStorage.removeItem(key);

}

Notice how I have a try and catch method around the setItem method. This is because the browser limits the LocalStorage of your domain to a certain amount. Most browsers have a default 5-10MB, so we should be ok in this situation, but it isn’t bad to remove the items if the LocalStorage does get too big.

jQuery(document).ready(getFromLocationStorage);

function getFromLocationStorage()

{

if(window.localStorage != null)

{

//use the same URL as our key

var url = location.href;

if(url.indexOf("#") != -1)

url = url.substr(0,url.indexOf('#'));

var key = "inputs-" + url;

try

{

var values = JSON.parse(localStorage.getItem(key));

for(var index in values)

{

jQuery("form input[name=" + index + "]").val(values[index]);

}

}

catch(e)

{

//it is entirely possible that there is nothing in the item

}

}

}

The first thing we do is use jQuery’s ready event to load in all of the input fields with the data from LocalStorage

jQuery(document).ready(getFromLocationStorage);

Our getFromLocationStorage method starts out very similar to our saveToLocalStorage method, we get the currentURL that we used as our key.

//use the same URL as our key

var url = location.href;

if(url.indexOf("#") != -1)

url = url.substr(0,url.indexOf('#'));

var key = "inputs-" + url;

I wish this blog post would be more complicated, but LocalStorage is so easy to use. It is super simple, to get our items from the localStorage, we just call LocalStorage’s getItem method.

try

{

var values = JSON.parse(localStorage.getItem(key));

for(var index in values)

{

jQuery("form input[name=" + index + "]").val(values[index]);

}

}

catch(e)

{

//it is entirely possible that there is nothing in the item

}

We then set the values of input field from the JSON data we received from the LocalStorage. That is it; seemless and simple. I can now see how Mozilla was hesitant to implement a SQLite database in its browser.

Here is the code in full.

<!DOCTYPE html

><html>

<head>

<title>Local Storage Like a Boss</title>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

<script type="text/javascript">

jQuery(document).ready(getFromLocationStorage);

function getFromLocationStorage()

{

if(window.localStorage != null)

{

//use the same URL as our key

var url = location.href;

if(url.indexOf("#") != -1)

url = url.substr(0,url.indexOf('#'));

var key = "inputs-" + url;

try

{

var values = JSON.parse(localStorage.getItem(key));

for(var index in values)

{

jQuery("form input[name=" + index + "]").val(values[index]);

}

}

catch(e)

{

//it is entirely possible that there is nothing in the item

}

}

}

function saveToLocalStorage()

{

if(window.localStorage != null)

{

//use the URL of the page as our "key"

var url = location.href;

if(url.indexOf("#") != -1)

url = url.substr(0,url.indexOf('#'));

var key = "inputs-" + url;

//use a dictionary as the keys

var values = {};

jQuery("form input").each(function(){

values[jQuery(this).attr("name")] = jQuery(this).val();

});

try

{

localStorage.setItem(key, JSON.stringify(values));

}

catch(e)

{

localStorage.removeItem(key);

}

}

}

</script>

</head>

<body>

<form>

<table>

<tr>First Name: </tr><td><input type="text" name="fname" id="fname"></input></td>

<tr>Last Name: </tr><td><input type="text" name="lname" id="lname"></input></td>

<tr><td colspan="2" style="text-align:right"><button onclick="saveToLocalStorage(); return false;">Save</button></td></tr>

</table>

</form>

</body>

Stay in touch

Bringing news to you

Subscribe to our newsletter

By clicking and subscribing, you agree to our Terms of Service and Privacy Policy

</html>


Related Content

thumbnail image

AlliPMG CultureCampaigns & Client WorkCompany NewsDigital MarketingData & Technology

PMG Innovation Challenge Inspires New Alli Technology Solutions

4 MINUTES READ | November 2, 2021

thumbnail image

Applying Function Options to Domain Entities in Go

11 MINUTES READ | October 21, 2019

thumbnail image

My Experience Teaching Through Jupyter Notebooks

4 MINUTES READ | September 21, 2019

thumbnail image

Working with an Automation Mindset

5 MINUTES READ | August 22, 2019

thumbnail image

3 Tips for Showing Value in the Tech You Build

5 MINUTES READ | April 24, 2019

thumbnail image

Testing React

13 MINUTES READ | March 12, 2019

thumbnail image

A Beginner’s Experience with Terraform

4 MINUTES READ | December 20, 2018

ALL POSTS