We all know about cookies. Web Storage is a new HTML5 API that provides similar functionality, but there are many differences between cookies and HTML5 Web Storage. Web Storage in a nutshell, allows us to store data in key-value pairs straight to the user's computer. If you're familiar with Android's SharedPreferences object, this post will be like a cakewalk to you...
NOTE: Unlike cookies, the information in localStorage doesn't expire. But what if you need to remove the data? Let's see...
Web Storage - Introduction
Web Storage allows us to store information in the form of key-value pairs in the user's computer in a fast and secure manner. Unlike cookies that allow small packets of data to be stored, web storage allows us to store proper data which is much larger in size than that allowed by cookies. This is why you will use web storage instead of cookies.
Also, unlike cookies, the data isn't sent to the server on each request, it is only returned to the scripts on your page when requested. This might be one reason to use cookies rather than using web storage.
NOTE: Web Storage isn't supported on Internet Explorer 7 and below...
Web Storage - Testing support
To test whether the current browser supports web storage or not you can use the following code.
if(typeof(Storage) !== "undefined") { // Yes, the browser supports web storage } else { // Nope, no support for web storage }
Web Storage - Storing Information
With web storage's localStorage object, we can store information in the user's computer as follows
localStorage.keyName = "Some value"; localStorage.setItem("keyName", "Some Value");These, are two different ways of storing a key/value pair in the user's computer where the key is "keyName" and value is "Some value".
NOTE: Unlike cookies, the information in localStorage doesn't expire. But what if you need to remove the data? Let's see...
Web Storage - Removing Information
The way you remove data with key "keyName" is as follows
localStorage.removeItem("keyName");
Web Storage - Retrieving Information
Let's assume we have a key called "firstName" with some value. The two ways to retrieve the value from the computer is:
var x = localStorage.getItem("firstName"); var x = localStorage.firstName; // Then do something with 'x'
Web Storage - Session storage
If you want to store data with web storage that should get expired after the session gets over (i.e. the browser is closed) use the sessionStorage instead of localStorage.
No comments:
Post a Comment