Data Storage

Cookie Limitations

Cookies

  • Sent with every HTTP request (in plain text)
  • Limited to 4KB each, 20 per domain. 300 per browser.
  • No real API

Local and Session Storage

  • Not sent to server (more secure / less bandwidth)
  • Limited to 5MB each
  • Long term or session long
  • Simmple API

localStorage

 
saveButton.addEventListener('click', function () {
  window.localStorage.setItem('value', textarea.value);
}, false);
textarea.value = window.localStorage.getItem('value');

Save text value on the client side (crash-safe)

	var el = document.querySelector('#myID');
	// place content from local storage on load if there is one
	el.innerHTML = window.localStorage.getItem('value');

Session Storage

  • use localStorage for persistent storage
  • use sessionStorage for per tab storage

Chrome: view storage: Inspector > Local Storage

  • Chrome
  • Safari
  • Firefox
  • Opera
  • IE 8
  • Well Supported!

Local Storage Code Lab

In this lab, we are going to play with the localStorage object. The user is going to be able to save, read and delete key/value pair from the localStorage

  1. In your labs folder, open the web_storage folder and edit the script.js file
  2. In the code, look for a // TODO 1. What we need to do here is to save a key/value pair into the localStorage. In this function, the key and the value entered by the user have been obtained (variables localKey and localValue)
  3. Look for a // TODO 2. What we need to do here is to remove a key/value pair from the localStorage using the key. The key is passed to the function you are editing with the variable key
  4. Look for a // TODO 3. What we need to do here is to remove every key/value pair from the localStorage
  5. Look for a // TODO 4. Here we want to iterate over the key/value pairs using their index. Thanks to the index, get the key of a key/value pair
  6. Look for a // TODO 5. Thanks to the key you have just got, get the value of the current key/value pair
  7. You should be done by now. Open index.html in a browser and try to add, see, and delete key/value pairs from the localStorage
Files

Web SQL

var db = window.openDatabase("DBName", "1.0", "description", 5*1024*1024); 
  db.transaction(function(tx) {
  tx.executeSql("SELECT * FROM test", [ ], successCallback, errorCallback);
});

ChromeView your database: Inspector > Resources > Databases

    • Chrome
    • Safari
    • Firefox
    • Opera
    • IE 8
    • Well Supported!

    Index dB

    var indexDatabase = window.indexedDB.open('Database Name');
    indexDatabase.onsuccess = function(event) {
      var db = event.srcElement.result;
      var transaction = db.transaction([], IDBTransaction.READ_ONLY);
      var currRequest = transaction.objectStore('ObjectStore Name').openCursor();
      currRequest.onsuccess = ...;
    };
    
    
    • Chrome 11
    • Safari
    • Firefox 4
    • Opera
    • IE 10

    HTML5 Offline Applications

    Next ➹