Close

JavaScript - HTML5 Web Storage

[Updated: Nov 22, 2016, Created: Nov 19, 2016]

HTML5 supports two kind of storage on the client browser: sessionStorage and localStorage


sessionStorage

Data is stored for the current session (data is cleared when browser is closed)


localStorage

Data is stored permanently unless developer 'clears' the data explicitly.


Interfaces

interface Storage {
 readonly attribute unsigned long length;
 DOMString? key(unsigned long index);
 getter DOMString? getItem(DOMString key);
 setter void setItem(DOMString key, DOMString value);
 deleter void removeItem(DOMString key);
 void clear();
};
  
interface WindowSessionStorage {
 readonly attribute Storage sessionStorage;
};
Window implements WindowSessionStorage;
 
interface WindowLocalStorage {
 readonly attribute Storage localStorage;
};
Window implements WindowLocalStorage;


Iterating

for (var key in localStorage){
   console.log(key)
}


Storage max limit

Different browser have different maximum limit for storage, for example google chrome has the limit of 5MB per website origin, which might change in a future version.

Always use a try/catch to decide on the limit:

 try {
  localStorage.setItem("myKey", "myData");
} catch(e) {
     //show a message to user
 }

To find out the current usage of storage:

var size = Math.round(JSON.stringify(localStorage).length / 1024);
console.log("Storage size:" + size + "K");

To test the limit in your browser:

for (var i = 0;  i < 1000000000; i++) {
    try {
        localStorage.setItem("key--"+i, "value"+i);
    } catch(e) {
        var storageSize = Math.round(JSON.stringify(localStorage).length / 1024);
        console.log("LIMIT REACHED: " + storageSize + "K");
        console.log(e);
        break;
    }
}

Output in chrome 54.x.xx

test.js:24 LIMIT REACHED:6576K
test.js:25 DOMException: Failed to execute 'setItem' on 'Storage': Setting the value of 'key--248406' exceeded the quota.(…)

See Also