Offline webapp. How to store data?

Hertzu picture Hertzu · Apr 15, 2013 · Viewed 11.8k times · Source

Introduction:

I want to develop a webapp to manage sports competitions. It must be able to run completely offline, store data locally and post the results online via AJAX whenever there is an internet connection available - this may be the day after.

Question:

How to store data using Javascript?

Aditional notes:

  • I don't want to use any server-side technology.
  • It must be secure like a database. I've read about cookies and html5 storage but none of them sound convincing.

Answer

Praveen Kumar Purushothaman picture Praveen Kumar Purushothaman · Apr 15, 2013

If you are supporting modern browsers, you can make use of HTML5 Local Storage.

Persistent local storage is one of the areas where native client applications have held an advantage over web applications. For native applications, the operating system typically provides an abstraction layer for storing and retrieving application-specific data like preferences or runtime state. These values may be stored in the registry, INI files, XML files, or some other place according to platform convention. If your native client application needs local storage beyond key/value pairs, you can embed your own database, invent your own file format, or any number of other solutions.

Example

// Save data to a the current session's store
sessionStorage.setItem("username", "John");

// Access some stored data
alert( "username = " + sessionStorage.getItem("username"));

// Get the text field that we're going to track
var field = document.getElementById("field");

// See if we have an autosave value
// (this will only happen if the page is accidentally refreshed)
if ( sessionStorage.getItem("autosave")) {
   // Restore the contents of the text field
   field.value = sessionStorage.getItem("autosave");
}

// Check the contents of the text field every second
setInterval(function(){
   // And save the results into the session storage object
   sessionStorage.setItem("autosave", field.value);
}, 1000);

Browser Compatibility


Older Browsers

Use Polyfill.