Conversation


Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!

Join the discussion and share your insights now!

Comments 0


advertisement

The Power of HTML5 Web Storage - Web Storage in HTML5

web storage in html5


Consider an email client, such as Gmail. To log in to your mail account in Gmail, you must enter your username and password.

The Stay signed in/Remember me check box specifies that the login details, such as Username and Password should be remembered by the computer.

Traditionally, over the last few decades, Web applications have been using cookies to store small amounts of information on a user's computer. A cookie is a file that stores user-related information and may either be temporary or permanent. Thus, in this case, a cookie can be created for login details which can be saved for a specified period on a user's computer.

However, the drawbacks of cookies are as follows:

  • Cookies slow down the performance of Web applications, as they are included with each HTTP request.
  • Cookies cannot be considered a safe means of the transmission of sensitive data.
  • Cookies cannot store large amounts of information, as they have a limitation of size of 4 KB.


To overcome these drawbacks and offer a solution to store data on the client side, W3C has designed a specification named Web Storage API.

Web storage provides functionality using which data can be stored on the client side for a session or beyond the session.



Web Storage in HTML5

Web storage is a W3C specification. It provides functionality for the storage of data on the client side which is on the user's machine. This data can cater to both temporary as well as permanent requirements. Certain browsers also refer to it as 'DOM Storage'. The advantage of such storage is that it offers more control than traditional cookies and is easy to work with.

Web storage was originally a part of the HTML5 specification, but now it is presented in a separate specification. It enables you to store a maximum of 5 MB of information per domain.

HTML5 Web applications make use of Web storage to implement client-side persistent storage.


1. Web Storage versus Cookies

Some key differences between cookies and Web storage are as follows:

  1. Cookies are meant to be read on the server side, whereas Web storage is available only on the client side. The server cannot read or write to it directly.

  2. Cookies are sent along with each HTTP request to the server, whereas Web storage data is not carried over to the server.

  3. Cookies can result in bandwidth overhead and thus lead to high costs, as they are sent with each HTTP request. The Web storage is stored on the user's hard drive, so it costs nothing to use.

  4. As mentioned earlier, with cookies, the information data that could be stored is 4 KB, whereas with Web storage, a large amount of data can be stored up to 5 MB.





2. Browser-specific Web Storage

Web storage is browser-specific. If a user visits a site in Google Chrome, any data will be stored in Google Chrome's Web storage store. Similarly, if the user revisits that same site in Firefox, the data saved earlier in Google Chrome will be unavailable. The location where Web storage data is stored depends on the browser. Each browser's storage is separate and independent, even if it is present on the same machine.

HTML5 Web storage is implemented natively in most Web browsers, so one can use it even when a third-party browser plug-in is not available.

Lists the support for various browsers for HTML5 Web storage.

  • IE - 8.0+ Onwards
  • Firefox - 3.6+ Onwards
  • Safari - 4.0+ Onwards
  • Chrome - 5.0+ Onwards
  • Opera - 10.5+ Onwards



Exploring Web Storage

The two types of HTML5 Web storage are namely, session storage and local storage. Both sessions are local storage enabled to store around 5 MB of data per domain. Before going into the details of these types, you must determine if the current version of your browser has support for HTML5 Web storage.

To check Tor browser support for HTML5 Web storage. A property named localstorage or sessionStorage is available as a global variable for the window object. If there is no support, the localStorage or sessionStorage properties will be undefined.

The script checks support for HTML5 Web storage in the browser.

<html>
<head>
    <script>
        function checkSupport() {
            if (('sessionStorage' in window) && window['sessionStorage'] !== null) {
                alert("Your browser supports Web Storage");
            } else {
                alert("Your browser does not support Web Storage");
            }
        }
    </script>
</head>
<body onload="checkSupport();">
</body>
</html>

Here, in the code, the if statement checks whether a property named sessionStorage exists in the global window object. If the property exists, it means that session storage is supported and an appropriate message is displayed to indicate the same. If however, the property does not exist, it means session storage is not supported in that browser and an appropriate message is displayed to indicate the same.


1. Session Storage

Session storage keeps track of data specific to one window or tab and discards it as soon as the user closes the tab (or window) that he/she was working with. Thus, even if you are visiting the same site in two different windows, each window will have its own individual session storage object. This means that each window contains a separate session storage object with distinct data. Session storage lasts for the entire duration of the session and hence, is not persistent.

Session storage makes use of named key/value pairs. The data is stored using the named key, whereas the data is retrieved by referring to that key. Both key-value pairs are enclosed in double quotes.

The key is a string, whereas the value stored in the key can be of any type of data, such as string, boolean, integer, or floating. Regardless of the type of data that is stored, it is stored internally as a string.

Therefore, storing and retrieving data of other types requires the use of functions to convert them into the appropriate data types.

For example, the function parseInt() is used to convert data into an appropriate JavaScript data type.

List some examples of named key/value pairs belonging to various data types.

  • Name - Sarah
  • book - C# Programming
  • Email - info@me.com
  • car - Toyota Innova
  • age - 28
  • uservalid - true


Several operations can be performed on the sessionStorage object.

These operations are described as follows:


Storing and retrieving data

The setItem () and getItem () methods are used to store and retrieve data from session storage respectively.

The syntax to use the setItem () and getItem () methods is as follows:

Syntax:


To assign data


sessionStorage. setItem (key, value);
Where,
Key: Is the named key to referring to the data

Value: Is the data to be stored


To retrieve data


var item = sessionStorage.getItem(key) ;
Where,
Item: Is the variable into which the data will be saved

Key: Is the named key to referring to the data


How to set and retrieve a name using the sessionStorage object?

<html>
<head>
    <script>
        function testStorage() {
            if (('sessionStorage' in window) && window['sessionStorage'] !== null) {
                sessionStorage.setItem('name', 'TEXVN');
                alert(sessionStorage.getItem('name') + ' is a Technology Company');
            }
        }
    </script>
</head>
<body onload="testStorage();">
</body>
</html>

The code stores the string literal 'Sarah' in the key name. This is done using the setItem() method. Then, the string literal is retrieved and displayed as an alert using the alert () method on the browser page. To retrieve the string literal, the getItem () method has been used in the code.

Note - Web Storage APl is supported in Internet Explorer from version 9 onwards.

Key names may not necessarily be given as strings. Even a number can be specified as a key name, though initially while stored, it will be converted to a string.

The script uses numbers as a key.

<html>
<head>
    <script>
        function testStorage() {
            if (('sessionStorage' in window) && window['sessionStorage'] !== null) {
                sessionStorage.setItem(6, 'The book was wonderful');
                var feedback = sessionStorage.getItem(6);
                alert(feedback);
            }
        }
    </script>
</head>
<body onload="testStorage();">
</body>
</html>

Here, in the code, the key is set to a numeric value of 6, but that does not mean that it is the sixth key. The name of the key is defined as 6 which is stored internally in the browser. The getItem() method is used to retrieve the value stored with that key. Finally, the value having the key 6 is displayed in the alert window.

Similar to other JavaScript objects, the sessionStorage object can be treated as an associative array.

Instead of using the getItem () and setItem () methods, an array subscript can be used to retrieve and assign the data.

For example, sessionStorage.setItem('name ', 'John'); can be written as

sessionStorage['name'] = 'John';

Similarly, alert (sessionStorage.getItem(' name ')); can be written as

alert(sessionStorage['name']):

<html>
<head>
    <script>
        function store() {
            if (('sessionStorage' in window) && window['sessionStorage'] !== null) {
                var name = document.getElementById('name').value;
                sessionStorage.setItem('username', name);
                var data = sessionStorage.getItem('username');
                sessionStorage.setItem('age', document.getElementById('age').value);
                var agevalue = parseInt(sessionStorage.getItem('age'));
                alert(data + ' is ' + agevalue + ' years old');
            }
        }
    </script>
</head>
<body>
    <form name="myform">
        <label>Enter Name:</label>
        <input type="text" id="name">
        <br />
        <label>Enter Age:</label>
        <input type="text" id="age">
        <br/>
        <input type="button" value="Submit" onclick="store()">
    </form>
</body>
</html>

In the code, the parseInt() method converts the specified argument to an integer format.


Removing and Clearing Data

It is also possible to remove and clear data from session storage. The removeitem() method is used to remove a particular item from the list.

The syntax for the removeItem() method is as follows:

Syntax:

sessionStorage.removeItem (key) ;

Where,

Key: Is the named key to the data

To remove the value associated with the key, the username set in the statement must be specified as follows:

sessionStorage.removeItem ( 'username') ;

Similarly, to clear all items present in the session storage, use the clear () method as shown:

sessionStorage. clear () ;

Also, the length attribute determines the number of key/value pairs present in storage.

var itemcount = sessionStorage.length;



Local storage

Unlike session storage, local storage enables the saving of data for longer periods on the user's computer, through the browser. The data is persistent and can be retrieved when a user visits the site again. In other words, local storage is used if data must be stored for more than a single session. A simple scenario would be to count the number of times a person has visited a Web page.

In terms of methods, local storage works similarly to session storage. It uses the same functions.

Such as setItem(), getItem(), removeItem(), and clear ().

The use of local storage to store the value of the username field and later retrieve the value from another Web page.

<html>
<head>
    <script>
        function store() {
            if ('localStorage' in window && window['localStorage'] !== null) {
                var username = document.getElementById('username').value;
                localStorage.setItem('username', username);
            } else {
                alert('Your browser does not support storage');
            }
        }
        function cancel_store() {
            if ('localStorage' in window && window['localStorage'] !== null) {
                localStorage.removeItem('username');
            } else {
                alert('Your browser does not support storage');
            }
        }
    </script>
</head>
<body>
    <form method="get" action="success.html">
        Username: <input type="text" id="username" value="" size="20" onblur="store()">
        <input type="submit" value="Submit">
        <input type="reset" value="Cancel" onclick="cancel_store()">
    </form>
</body>
</html>

Here, in the code, support for the localstorage object is checked in the current browser. If it is supported, then the contents of the username box are retrieved and stored in a variable named username. Then, the content of this variable is assigned to the local storage object with the key set to username. If the localstorage object is not supported, an appropriate message is displayed in the alert window.

Also, the function cancel_store () is invoked when the user clicks Cancel. In the cancel_store () function, the removeItem () method removes the specified key and its value from local storage.

When the Submit button is clicked, the user is redirected to the Web pages.
success.html, which displays the value stored with the key, username.


The success.html page retrieves a value from local storage and displays it in the browser.

<head>
    <script>
        function print() {
            var username = localStorage.getItem('username');
            document.getElementById('lblMsg').innerHTML = 'Username: <b>' + username + '</b>';
        }
    </script>
</head>
<body onload="print()">
    <label id="lblMsg"></label><br>
</body>
</html>

Here, in the code, the getItem () method of local storage retrieves the value from the username key and stores it in the variable username. Then, the value of the variable username is displayed in the <label> tag.


HTML5 HTML Web Storage HTML Web storage Web storage API localstorage javascript what is local storage local storage vs session storage browser storage web storage in HTML5 web storage vs cookies Local storage

advertisement