In one of our previous article, we have explained toggle class based on pure Javascript, in this article, I have explained about local storage in Javascript, when the developer had to save some details on the user's browser, we used to save it in cookies of the browser, even we are still doing it on many websites, but in HTML5 concept of local storage was introduced, which can be very useful, you can save data in user's browser using HTML5 local storage.

What is local storage?

HTML5's web storage feature lets you store some information locally on the user's computer, similar to cookies but it is more secure and faster. The information stored in the web storage isn't sent to the web server as opposed to the cookies where data sent to the server with every request, thereby slowing down your web application by transmitting the same data and the data is also unencrypted in it.

HTML5-Local-storage-in-javscript

So, there are two types of web storage :

  1. Local storage — The local storage uses the localStorage object to store data for your entire website, permanently, i.e. it is designed for storage that spans multiple windows, and lasts beyond the current session. In particular, Web applications may wish to store megabytes(MB) of user data, such as entire user-authored documents or a user's mailbox, on the client-side for performance reasons.

    You can store strings, numbers, objects, complex objects arrays etc. Let's see the syntax to store & fetch stuff from your browser’s storage but do not store sensitive data like passwords, account nos, etc..
  2. Session storage — The session storage uses the sessionStorage object to store data on a temporary basis, for a single window (or tab). The data disappears when the session ends i.e. when the user closes that window (or tab).

Local Storage Vs Cookies

HTML5 local storage is similar to cookies in that both mechanisms can be used to store data in the browser between HTTP requests. But there is a difference between HTML5 local storage and cookies.

Cookies are small pieces of data which a server can store in the browser. The cookie is sent by the browser along with all future HTTP requests to the server that set the cookie. Cookies cannot be bigger than 4KB in total.

HTML5 local storage is set via JavaScript executed in the browser. HTML5 local storage properties are never sent to any server - unless you explicitly copy them out of the local storage and appends them to an AJAX request. HTML5 local storage can store somewhere between 2MB and 10MB data in the browser (per origin - domain name). Exactly how much data is allowed depends on the browser. A limit of 5MB to 10MB is most common.

HTML5 local storage  is more secure and faster than Cookies.

Using Local Storage In HTML5 with Javascript

Using local storage in modern browsers is very easy. All you have to do is modify the localStorage object in JavaScript. You can do that directly or you can use the setItem() and getItem() method:

localStorage.setItem('favoritecolor','blue');

The first argument is the identifier you’ll later use to get the data out again. The second is the data you want to store.

To get the above item you can use below code in javascript

var color = localStorage.getItem('favoritecolor');
// output : "blue"

Local storage can only save strings, so storing objects requires that they be turned into strings using JSON.stringify - you can’t ask local storage to store an object directly because it’ll store “[object Object]”, which isn't correct.

So suppose you want to store user_name and it's api_key using localStorage you need to do it like this

localStorage.setItem('user', JSON.stringify({
    username: 'LocalStorageInHTML',
    api_key: '123qawithexperts'
}));

var user = JSON.parse(localStorage.getItem('user'));

But, JSON is not supported in all browser. You can also use jQuery’s parse JSON method if you are already using jQuery. Else you can use the same logic jQuery is using to parse the JSON.Excerpt from jquery-1.11.0.js

jQuery.parseJSON = function( data ) {
	// Attempt to parse using the native JSON parser first
	if ( window.JSON && window.JSON.parse ) {
		// Support: Android 2.3
		// Workaround failure to string-cast null input
		return window.JSON.parse( data + "" );
	}
 
	var requireNonComma,
		depth = null,
		str = jQuery.trim( data + "" );
 
	// Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
	// after removing valid tokens
	return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) {
 
		// Force termination if we see a misplaced comma
		if ( requireNonComma && comma ) {
			depth = 0;
		}
 
		// Perform no more replacements after returning to outermost depth
		if ( depth === 0 ) {
			return token;
		}
 
		// Commas must not follow "[", "{", or ","
		requireNonComma = open || comma;
 
		// Determine new depth
		// array/object open ("[" or "{"): depth += true - false (increment)
		// array/object close ("]" or "}"): depth += false - true (decrement)
		// other cases ("," or primitive): depth += true - true (numeric cast)
		depth += !close - !open;
 
		// Remove this token
		return "";
	}) ) ?
		( Function( "return " + str ) )() :
		jQuery.error( "Invalid JSON: " + data );
};

You can check if Window.JSON is present. if not, load it up.

if(!(window.JSON && window.JSON.parse))
{
    (function() {
  function g(a){var b=typeof a;if("object"==b)if(a){if(a instanceof Array)return"array";if(a instanceof Object)return b;var c=Object.prototype.toString.call(a);if("[object Window]"==c)return"object";if("[object Array]"==c||"number"==typeof a.length&&"undefined"!=typeof a.splice&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("splice"))return"array";if("[object Function]"==c||"undefined"!=typeof a.call&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("call"))return"function"}else return"null";
  else if("function"==b&&"undefined"==typeof a.call)return"object";return b};function h(a){a=""+a;if(/^\s*$/.test(a)?0:/^[\],:{}\s\u2028\u2029]*$/.test(a.replace(/\\["\\\/bfnrtu]/g,"@").replace(/"[^"\\\n\r\u2028\u2029\x00-\x08\x10-\x1f\x80-\x9f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g,"")))try{return eval("("+a+")")}catch(b){}throw Error("Invalid JSON string: "+a);}function i(a,b){var c=[];j(new k(b),a,c);return c.join("")}function k(a){this.a=a}
  function j(a,b,c){switch(typeof b){case "string":l(b,c);break;case "number":c.push(isFinite(b)&&!isNaN(b)?b:"null");break;case "boolean":c.push(b);break;case "undefined":c.push("null");break;case "object":if(null==b){c.push("null");break}if("array"==g(b)){var f=b.length;c.push("[");for(var d="",e=0;e<f;e++)c.push(d),d=b[e],j(a,a.a?a.a.call(b,""+e,d):d,c),d=",";c.push("]");break}c.push("{");f="";for(e in b)Object.prototype.hasOwnProperty.call(b,e)&&(d=b[e],"function"!=typeof d&&(c.push(f),l(e,c),c.push(":"),
    j(a,a.a?a.a.call(b,e,d):d,c),f=","));c.push("}");break;case "function":break;default:throw Error("Unknown type: "+typeof b);}}var m={'"':'\\"',"\\":"\\\\","/":"\\/","\u0008":"\\b","\u000c":"\\f","\n":"\\n","\r":"\\r","\t":"\\t","\x0B":"\\u000b"},n=/\uffff/.test("\uffff")?/[\\\"\x00-\x1f\x7f-\uffff]/g:/[\\\"\x00-\x1f\x7f-\xff]/g;
  function l(a,b){b.push('"',a.replace(n,function(a){if(a in m)return m[a];var b=a.charCodeAt(0),d="\\u";16>b?d+="000":256>b?d+="00":4096>b&&(d+="0");return m[a]=d+b.toString(16)}),'"')};window.JSON||(window.JSON={});"function"!==typeof window.JSON.stringify&&(window.JSON.stringify=i);"function"!==typeof window.JSON.parse&&(window.JSON.parse=h);
})();
}
//source : https://stackoverflow.com/questions/2277405/json-stringify-missing-from-jquery-1-4-1/9948488#9948488

Now,  you can use   JSON.parse(object);   JSON.stringfy(string);.

Clearing the Local Storage

If you want to delete all properties stored in the sessionStorage or localStorage objects, you can use the clear() function. Here is a clear() function call example:

sessionStorage.clear();

localStorage.clear();

You can also clear local storage based on the key name, for example

localStorage.removeItem("MyKey");

Reading Number of Properties Stored

You can read the number of properties stored in the sessionStorage or localStorage objects using the length property, like this:

var length = sessionStorage.length;

var length = localStorage.length;

Iterating Keys in the Local Storage

You can iterate the keys (property names) of the key-value pairs stored in the sessionStorage or localStorage, like this:

for(var i=0; i < sessionStorage.length; i++){

    var propertyName = sessionStorage.key(i);

    console.log(  i + " : " + propertyName + " = " +
            sessionStorage.getItem(propertyName));
}

The sessionStorage.length property returns the number of properties stored in the sessionStorage object.

Browser support for local storage is not 100%, but you can use it on the latest browser, check here for more details.

You may also like to read:

Form validation in javascript

How to get user location using Javascript / HTML5 Geolocation?

Useful Javascript Unit Testing Frameworks

Best Javascript Charting Libraries

Convert html to word with images (Using Javascript OR Using jQuery plugin)

Using Google maps Javascript api in HTML (Show location with Marker)