Sam Croft

A designer/developer on HTML, CSS, JavaScript and PhoneGap

Quick tip: using HTML5 localstorage to store JSON objects on a device in your PhoneGap app

  • 26 comments

Filed in: android, Cordova, iOS, javascript, JSON, PhoneGap

I’ve written a couple of articles about loading remote data into PhoneGap apps (sans framework), but I haven’t mentioned a good little method of storing that data on the device so you don’t need to request it from a server again. This is a quick tip for how you can do that.

Of course, it depends on the type of data that you are loading from your server in the first place. You wouldn’t necessarily want to store data that would be out of date quickly – such as share prices or live sports scores. But there will certainly be times when you want to save the data you’ve just loaded for use at a later time, without having to load it again.

Loading data from a remote source

When loading data from a remote source I’d use jQuery or Zepto’s ajax() function like this:

$.ajax({
    url: 'http://your-app.com/api/news/12',
    dataType: 'JSONp',
    success: function(data, status) {
        $.each(data, function(key, value){
            //handle the data                
        });
    },
    error: function() {
        //handle the error
    }
}

In this example I’m accessing a fictional data source to load a news article.

Once the article is loaded the user might browse another article but later on may return to read this particular one again. You could load the article from your server again. But that’s a bit inefficient if you have already loaded it before. You could just as easily store the article locally, using HTML5′s localStorage, on the device and request the details from there. That’s pretty simple to setup.

HTML5 local and session storage

HTML5 introduced several methods of storing data within the clients browser. Two of these methods are local and session storage. localStorage saves data until it is removed by the client or app whereas sessionStorage saves data until the session ends, when the browser window/tab is closed.

Mark Pilgrim sums up HTML5 local storage as:

a way for web pages to store named key/value pairs locally, within the client web browser. Like cookies, this data persists even after you navigate away from the web site, close your browser tab, exit your browser, or what have you. Unlike cookies, this data is never transmitted to the remote web server (unless you go out of your way to send it manually).

Storing a key/value pair is very straightforward:

localStorage.setItem('yourKeyName', 'your value');

This works great for simple key/value pairs.

Storing a JSON object in local storage

Attempting to store a JSON object, or an ordinary array of data, in local storage will yield an error. Local storage requires you to store strings of information. To store a JSON object in local storage you will need to convert it into a JSON-formatted string, using the JSON.stringify() function.

Referring back to the ajax example above, we could take the data object and stringify it:

var dataToStore = JSON.stringify(data);

Then it’s just a case of storing the new JSON-formatted string in local storage:

localStorage.setItem('someData', dataToStore);

Loading a JSON object from local storage

Now that the JSON object is stored locally you can access the data directly from the device, without having to make a request to the remote server. However, because the object was previously converted to a JSON-formatted string, you will have to reverse the effects of the stringify function before you can access the data within the object. This is easily done through use of the JSON.parse() function:

var localData = JSON.parse(localStorage.getItem('someData'));

Now you can access the object and handle it as you normally would:

$.each(localData, function(key, value){
    console.log(key + ' = ' + value);
});

Using PhoneGap’s local storage api

The above example will work in any modern browser as well as in your PhoneGap app, but PhoneGap also provides local storage access via its api:

//setting an item
window.localStorage.setItem('key', 'value');

//loading an item
var value = window.localStorage.getItem('key');

The only difference here being window. prepended to the ordinary localStorage methods.

Putting it all together in a PhoneGap app

Taking all of this into account you might end up with something like this:

$.ajax({
    url: 'http://your-app.com/api/news/12',
    dataType: 'JSONp',
    success: function(data, status) {
        $.each(data, function(key, value){
            //handle the data                
        });
		
        var localData = JSON.stringify(data);
		
        window.localStorage.setItem('newsArticle12', localData);
    },
    error: function() {
        //handle the error
    }
}

And when you want to get access to that data the next time:

var localData = JSON.parse(window.localStorage.getItem('newsArticle12');

$.each(function(key, value){
	//handle the data
});

This is a useful technique to use in PhoneGap apps, it can be a significant optimisation when used appropriately. It reduces server requests and loads your [previously loaded] data faster.

Some considerations

There are some considerations with using local storage though.

There is a limit to how much data you can store via localStorage – approximately 5mb. If you are dealing with a lot of data you could soon reach that limit.

The main consideration should always evaluating the type of data that you are storing locally. Maybe sessionStorage is the better choice if your users require up to date information each time they open your app. Or maybe you need to include an expiry data in your JSON object and check against that before serving the data.

Related articles

About the author

I'm Sam Croft - a thirtysomething designer/developer and co-founder of Running in the Halls Ltd—a web and app development studio in Huddersfield, UK. I was educated in graphic design and now specialise in front-end web and app development; my main passion being usability and accessibility. I strongly believe web apps (vs native) are the future and love developing for mobile using the wonderful PhoneGap.

I am a massive sports fan - Formula One in particular. I live in the Pennines with my beautiful wife, Alex. Occasionally I own a large scruffy beard.

I tweet about all of my interests - you should follow me. I also have a .

  • Jamie Reynolds

    Nice write up Sam. I used local storage extensively in my last phonegap project and it worked very well.

    As weather app, storing the huge list of locations reports are available for made sense. There is no point fetching that data from the API each time a user wants to search for a location. Plus – once stored the this whole process is much faster.

    However, the expiry date point is a good one. You need to have some method of updating the data.

  • http://samcroft.co.uk/ Sam Croft

    Thanks Jamie. Which weather app was this? Would love to have a look :]

  • Jamie Reynolds

    Sure! I’ll get you a promo code.

  • http://samcroft.co.uk/ Sam Croft

    Ah great, look forward to having a play!

  • Burak

    can u make a tutorial how i can make app they load data from external server (images, text etc.) and save it offline. Please :D :D :D

    PS: Love u r articles

  • Mirco

    Hi,

    this is my landmarks.php, but dosn’t work

    1, ‘b’ => 2, ‘c’ => 3, ‘d’ => 4, ‘e’ => 5);
    $data = json_encode($arr);

    echo $data;
    ?>

  • http://www.ncn.co/ Jason Graves

    Nice post. With regards to placing an expiry data or date into your json object… I went a different route. I’m also storing a large json object as a string in localstorage, but I just added a second localstorage variable/record (lets call it “country-state-json-version”) containing a version number for my JSON object. This way when my app loads I can quickly compare my local version with my latest version on the server to determine if I need to reload the json obj.

  • http://www.ncn.co/ Jason Graves

    Checkout HTML5′s Cache Manifest feature… That’s how you would accomplish loading external resources such as images and files, and saving them for offline use.

    http://diveintohtml5.info/offline.html
    http://www.w3schools.com/html/html5_app_cache.asp

  • http://samcroft.co.uk/ Sam Croft

    Hi Jason, that’s very clever. I will definitely use that approach from now on. Thanks for sharing!

  • Pingback: Quick tip: using HTML5 localstorage to store JSON objects on a device in your PhoneGap app | Snabbels Blog

  • Vee

    Hi, how to know the right url for the application?

  • platzh1rsch

    perfect, exactly what I was looking for. Thx a lot!

  • Mark

    Thanks for the info, helpful~~

  • Kyle Traveler

    Thanks

  • Yingshen Chen

    web app is the future, no doubt

  • Deepan

    Sam, iam Working in Social Networking app like facebook walls… is there any metodolgy to folow that wall post storages, and Static storage as well

  • Simona Butnaru

    Hi Sam. I enjoyed this article and it was easy to understand. Still I have one question, how can I store locally an JSON object bigger than 5mb? Thanks.

  • http://samcroft.co.uk/ Sam Croft

    Hi Simona,

    That’s a large JSON object! I think you would need to use the HTML5 file API. There is a Cordova plugin https://github.com/apache/cordova-plugin-file/blob/master/doc/index.md – I haven’t used it before, but it should be good for a 5mb file.

  • Simona Butnaru

    What do you think about Storage support from Phonegap? As I was doing research I found that using Sql Lite Database is a good way to manipulate data and storage objects of big dimension.

  • http://samcroft.co.uk/ Sam Croft

    That would work. You’d have to use a native SQLite database though as I believe the storage API for PhoneGap just uses the HTML5 localStorage and Web SQL database API. Which both have 5mb limits. This plugin looks good – https://github.com/brodysoft/Cordova-SQLitePlugin

  • Simona Butnaru

    I’ll have a look. Thanks Sam, for your help. Have a nice weekend!

  • http://samcroft.co.uk/ Sam Croft

    No problem. You have a nice one too!

  • saurabhgupta0508

    Hi ,

    I am using local storage in my cordova app with localstorage-db.js for sql like functinality. It provides a neat solution, but i am just wondering about the life of localstorage. Can local storage be used as a alternative to the native storage provided in the native apps. Whether it will be flushed if we update the application.

  • http://samcroft.co.uk/ Sam Croft

    Hi,

    In my experience localstorage will persist until the app is uninstalled, or the data/cache is cleared manually in settings. App updates should not affect localstorage.

  • Midix

    Does localStorage or PhoneGap’s localStorage work on Windows Phone? I tried localStorage on my desktop IE in a local file and IE told me that it does not support localStorage for local files. As we know, PhoneGap/Cordova apps are essentially a bunch of files accessed locally from a folder, thus I’m curious if IE on Windows Phone also has the restriction regarding localStorage and local files.

  • http://samcroft.co.uk/ Sam Croft

    Hi Midix,

    It sounds like Windows has some quirks with localstorage. I noticed this on Phonegap’s documentation…

    http://docs.phonegap.com/en/3.0.0/cordova_storage_storage.md.html#Storage

    Windows Phone 7 Quirks

    Dot notation is not available on Windows Phone 7. Be sure to use setItem or getItem, rather than accessing keys directly from the storage object, such as window.localStorage.someKey.