HTML5 localStorage code sample

See HTML5 storage Notes

//========================================//
// 3 Ways to manipulate data 
//========================================//
var storage = window.localStorage;


//-- 1. Using Dot-notation ---------------//
if (storage.myMessage1 === undefined) {
    console.log('No message yet');
    storage.myMessage1 = 'Message 1';
} else {
    console.log('My Message: ', storage.myMessage1);
}


//-- 2. Using Get-Set --------------------//
if (storage.getItem('myMessage2') === null) {
    console.log('No message yet');
    storage.setItem('myMessage2', 'Message 2');
} else {
    console.log('My Message: ', storage.getItem('myMessage2'));
}


//-- 3. Using Bracket --------------------//
if (storage['myMessage3'] === undefined) {
    console.log('No message yet');
    storage['myMessage3'] = 'Message 3';
} else {
    console.log('My Message: ', storage['myMessage3']);
}


//========================================//
// Remove data
//========================================//
storage.removeItem('myMessage1'); // remove data with a given key
storage.clear();                  // clear all storage data


//========================================//
// Iterate all key-value pair in storage:
//========================================//
for(var i=0; i<storage.length; i++) {
    key = storage.key(i);
    console.log(key, ': ', storage[key]);
}
Advertisements

HTML5 Web Storage Notes

  • string-based
  • normally have 5 megabytes of space in a browser. However, 1 character does not equal to 1 byte in web character encoding.
  •  sessionStorage
    • API is used exactly the same way as localStorage (see below for demo)
    • Refers to browser tab session, not user sessions
    • Data live forever as long as the tab is not being closed
    • Data is not shared across browser window/tab
  • in-private browsing:
    • localStorage will act like sessionStorage
    • Safari won’t store any data at all in private mode

See HTML5 localStorage code