Alex Rivera | Logout

Offline webapp. How to store data?

Asked 2013-04-15T03:08:17.783
8

Introduction:

App must be able to run completely offline, store data locally and post it online via AJAX whenever there is an internet connection available - this may be some days later.

Question:

How to store data using Javascript?

Additional 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.
Edit
Report

1 Answer

2

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.

answered 2013-04-15T03:11:11.100

Your Answer