Web storage vs cookie

Old browsers already support cookies which can store small size data(Up to 4k bytes cookies per domain). But the cookie has to be sent to web server through http requests. The mechanism reduces page-loading speed and makes a website less secure. On the contrary, web storage can address the issues above by storing larger size data(Up to 10M bytes per domain in IE8 and up to 5M bytes per domain in Safari and Firefox) locally without http requests; however, the con is that the data is not encrypted. There are two kinds of web storage: local storage and session storage.

Local storage

With local storage, a user can still keep stored key-value pair even though the user closes and reopens a browser. Note: in private browsing mode, Safari and iOS Safari don’t support localStorage. In the statement localStorage.setItem("yourName", "James");, “yourName” is the key and “James” is the corresponding value; and localStorage.setItem() sets the key-value pair. localStorage.getItem("yourName") gets the value of key-value pair. alert() shows up a message box.

Source Code Box: Local storage | Browser: IE8+,Firefox25+,Chrome31+,Safari7+,Opera17+,iOS3.2+,Android2.1+

Local storage expiration

To better understand local storage mechanism, you need firstly to run the local storage code above. Then close your browser and reopen this web page to run the code below. You will see that the local storage “yourName” will still keep the value “James”.

Source Code Box: Local storage expiration

Session storage

Different from local storage, session storage can only keep stored key-value pair in one session; closing a browser will loose session storage.

Source Code Box: session storage | Browser: IE8+,Firefox25+,Chrome31+,Safari7+,Opera17+,iOS3.2+,Android2.1+