<< Back to the blog

HTML5 - Local Storage

By @islamzatary

List of Advanced HTML5 Topics:

Local Storage or client side storage


Local Storage is simple JavaScript API in the browser for storing Key value pairs that are persistent and you are not limited to 4k of memory.

Local Storage vs Cookies

Browsers supports LocalStorage

Can I Use LocalStorage


Simple Example:

if (window["localStorage"]) { localstorage.setItem("key1","value1"); var value=localstorage.getItem("key1"); alert(value); } So its an array

Local Storage stores only string value, so if you need to put in shopping counts and prices in Local Storage you need to use parsing.
parseInt(), parseFloat().

Because it’s an array you access the data like this:

var value=localStorage["key1"];

LocalStorage get access on Length and Key: See file

Remove keys:
or directly from browser.

Continue to LocalStorage

Clean entries By localStorage.clear();

Until now Now there is no expiry added.
Replace all previous localStorage with sessionStorage so your data will store during browser session.

The Big Question is: What happens if 5MB storage exceeds?
should throw QUOTA_EXCEEDED_ERR exception.
Don’t forget to use try,catch loop, because its may crash the browser if it exceeds 5mb storage. See Example

Important things to be remember while using Local Storage API:-

There is no naming conventions available for HTML5 LocalStorage keys,but those should be unique.
So you need to select naming scheme for your local storage that won’t conflict with other applications at the same domain.
And if you want to store arrays or objects into local storage use JSON.stringify to store the value and JSON.parse to retrive the value.

Complete Exampl:See localstorage_example.html


HTML5 LocalStorage


Wrapping up

<< Back to the blog

by @islamzatary