How to use Local Storage and Session Storage Feature of HTML 5.0 ?



Using HTML 5.0, Webpage can store data locally within the user’s browser . Previously I was possible only by using cookie concept but there was storage problem. Many browsers have size limit of 4,096 bytes for a single cookie. But using “local Storage” we store upto 5mb data on browser.

For storing data there are 2 options available
a. Using Local storage : Store data with no expiration date.
b. Using Session Storage : Store data for one session only

Syntax for using Local Storage using Javascript


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="LocalStorage.aspx.cs" Inherits="LocalStorage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function SaveData() {
            if (typeof (Storage) !== "undefined") {
                window.localStorage["myKey"] = document.getElementById("txtName").value;
                
                alert("Data has been Save in LocalStorage");
            }
            else {
                alert("Sorry this browser doesnot suppot HTML5");
            }
        }

        function FetchData() {

            document.getElementById("txtOP").value = window.localStorage["myKey"];
          
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox ID="txtName" runat="server" />
    <br />
    <br />
    <asp:Button ID="btnSubmit" runat="server" OnClientClick="SaveData()" Text="Submit" />

    <br />
    <br />
    <asp:Button ID="btnDisp" runat="server" OnClientClick="FetchData()" Text="Click here to Fetch Data" />
    <br /><br />
    <asp:TextBox ID="txtOP" runat="server" />
    
    </div>
    </form>
</body>
</html>


Note Syntax will same for SessionStorage.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.