localStorage–Avoid Cookies!

With introduction of HTML 5 localStorage,  storing of small chunks of information in Cookies got eliminated! HTML 5 LocalStorage is an awesome feature which makes the storing and retrieving the data pretty easy.

Let us look at a simple example to demonstrate the HTML 5 LocalStorage feature!

The below example shows how to store “UserName” in to LocalStorage and retrieve it back!

<!DOCTYPE html>
<html>
<head>
    <title>HTML 5 World!!!</title>
</head>
<body>
    <header>HTML 5 Local Storage Demo!</header>
        <input type="text" id="txtUserName" />
        <input type="button" value="Save" onclick="SaveToOfflineStorage();" />
        <label id="msg" ></label>
    <footer>Copyright &copy;2011</footer>

    <script type="text/javascript">

        if (localStorage) {

            var UserName = localStorage.getItem("UserName");
            document.getElementById('txtUserName').value = UserName;
        }

        function SaveToOfflineStorage() {
            try {
                //If localStorage supports with the browser
                if (localStorage) {
                    var txtValue = document.getElementById('txtUserName').value;
                    localStorage.setItem("UserName", txtValue);
                    document.getElementById('msg').innerHTML = "Saved Successfully!";
                }
            }
            catch (err) {
                document.getElementById('msg').innerHTML = err.Description;
            }
        }
    </script>
</body>
</html>

NOTE: The above example works on HTML 5 Compatible browsers – Microsoft IE9 & above, Mozilla Firefox 3.5 & above, Google Chrome etc.,

You can also take advantage of sessionStorage,  which stores data temporarily for particular browser session! It works similar like Session in ASP.NET, JSP etc.,

Happy HTML5 Web Programming!!!

2 Comments

  1. I understand that the only way to get my php/js web app not to reset each time the visitor click on iphone app icon is to put the cookies in localstorage. Have you seen code for this? Thanks

    1. Hi Paul,
      May be! You can try storing data in localStorage! As far my knowledge, it should work fin in Apple iPhone!

      Regarding code, you can try with the same code, which I has posted in my blog post.

      Hope it helps u…

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 )

Google+ photo

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

Connecting to %s