How to store data in localStorage and sessionStorage
localStorage and sessionStorage in HTML5
In this article we will learn two important web storage capacity
of HTML5 . They are localStorage and sessionStorage. We know that HTML5 gives
the facility to store data in computer browser. We can tell that this is the
updated version of cookie. Unlike cookie (which gives only 4KB data storage) it
can store near to 5MB data but depends on browser. To store data in browser we
will take help of JavaScript.
So, if our browser supports HTML5 then we can use
localStorage and sessionStorage to store user’s data. In this article we will
see them one by one.
localStorage in action
Let’s see how to implement localStorage in application. Take
one empty .aspx/.html page and write below code into it.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScriptTest.JavaScript" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function TestStorage() {
if (typeof (Storage) !== "undefined") {
localStorage.name = "Sourav Kayal";
alert("Local Storage:- " + localStorage.name);
}
else
alert("Browser does not support storage");
}
</script>
</head>
<body onload="TestStorage()">
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Here is sample output.
When we perform localStorage operation, the data saves in browser.
It is persistence storage ,means even if user close the browser the data will
not get lost. When user will start new session in same browser we can get this
data from local storage area. The data will not be deleted if we do not delete
it explicitly or uninstall the browser.
sessionStorage
sessioStorage is another example of storage in HTML5. The difference
between localStorage and sessionStorage is that the sessionStorage data will
get delete when the current session will close. IT means when user will close
the browser window the data will get delete. Try to understand sessionStorage
with small example.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="JavaScriptTest.JavaScript" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function TestStorage() {
if (typeof (Storage) !== "undefined") {
sessionStorage.name = "Sourav Kayal";
alert("Information from sessionStorage:- " + sessionStorage.name);
}
else
alert("Browser does not support storage");
}
</script>
</head>
<body onload="TestStorage()">
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Here is sample output
Conclusion:-
In this quick article we have learned how to store data in
localStorage and sessionStorage. Hope you have understood the concept. In next
example we will learn more about localStorage and sessionStorage.