HTML 5 Web Storage

HTML5 web storage, a better local storage method than cookies.

What is HTML5 web storage?

Use HTML5 to store the user’s browsing data locally.

Earlier, local storage used cookies. But web storage needs to be more secure and fast. These data will not be stored on the server, but these data are only used for user request website data. It can also store a large amount of data without affecting the performance of the website.

Data exists as a key/value pair, and the data of a web page is only allowed to be accessed and used.

localStorage and sessionStorage 

The two objects that the client stores data are:

  • localStorage-It is used to save the data of the entire website for a long time. The saved data has no expiration time until it is manually removed.
  • sessionStorage-Used to temporarily save the data of the same window (or tab), which will be deleted after closing the window or tab.

Before using web storage, you should check whether your browser supports localStorage and sessionStorage:

if ( typeof ( Storage ) !== " undefined " ) { // Yes! Support localStorage sessionStorage object!

    
    // Some code.....
} else { // Sorry! Web storage is not supported.  
    
}

localStorage object

There is no time limit for the data stored in the localStorage object. The data will still be available after the next day, the second week, or the next year.

Example

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>Novice Tutorial</title> 
</head>
<body>

<div id="result"></div>
<script>
if(typeof(Storage)!=="undefined")
{
  localStorage.sitename="Novice Tutorial";
  document.getElementById("result").innerHTML="Site name:" + localStorage.sitename;
}
else
{
  document.getElementById("result").innerHTML="Sorry, your browser does not support web storage.";
}
</script>

</body>

Example analysis:

  • Use key=”sitename” and value=”novice tutorial” to create a localStorage key/value pair.
  • Retrieve the value with the key value “sitename” and insert the data into the element with id=”result”.

The above example can also be written like this:

// Store
localStorage . sitename = " Novice Tutorial " ;
 // Search
document . getElementById ( " result " ) . innerHTML = localStorage . sitename ;

Remove “sitename” in localStorage:

localStorage . removeItem ( " sitename " ) ;

Regardless of whether it is localStorage or sessionStorage, the available APIs are the same. The commonly used APIs are as follows (take localStorage as an example):

  • Save data: localStorage.setItem(key,value);
  • Read data: localStorage.getItem(key);
  • Delete a single data: localStorage.removeItem(key);
  • Delete all data: localStorage.clear();
  • Get the key of an index: localStorage.key(index);

Tip: Key/value pairs are usually stored as strings. You can convert the format according to your needs.

The following example shows the number of times the user clicked the button.

The string value in the code is converted to a numeric type:

Example


<html>
<head>
<meta charset="utf-8"> 
<title>Novice Tutorial</title> 	
<script>
function clickCounter()
{
	if(typeof(Storage)!=="undefined")
	{
		if (localStorage.clickcount)
		{
			localStorage.clickcount=Number(localStorage.clickcount)+1;
		}
		else
		{
			localStorage.clickcount=1;
		}
		document.getElementById("result").innerHTML=" You have clicked the button " + localStorage.clickcount + " Times ";
	}
	else
	{
		document.getElementById("result").innerHTML="Sorry, your browser does not support web storage.";
	}
}
</script>
</head>
<body>
<p><button onclick="clickCounter()" type="button">Check</button></p>
<div id="result"></div>
<p>Click this button to see the increase of the counter.</p>
<p>Close the browser tab (or window) and reopen this page, the counter will continue to count (not reset).</p>
</body>
</html>

sessionStorage object

The sessionStorage method stores data for a session. When the user closes the browser window, the data will be deleted.

How to create and access a sessionStorage:

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>Novice Tutorial</title> 
<script>
function clickCounter()
{
	if(typeof(Storage)!=="undefined")
	{
		if (sessionStorage.clickcount)
		{
			sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
		}
		else
		{
			sessionStorage.clickcount=1;
		}
		document.getElementById("result").innerHTML="You have clicked the button in this conversation" + sessionStorage.clickcount + "Times";
	}
	else
	{
		document.getElementById("result").innerHTML="Sorry, your browser does not support web storage";
	}
}
</script>
</head>
<body>
<p><button onclick="clickCounter()" type="button">Check</button></p>
<div id="result"></div>
<p>Click this button to see the increase of the counter.</p>
<p>Close the browser tab (or window), reopen this page, and the counter will be reset.</p>
</body>
</html>

Web Storage develops a simple website listing program

The website list program implements the following functions:

  • You can enter the website name and URL, and save it in localStorage with the website name as the key;
  • According to the website name, find the URL;
  • List all currently saved websites;

The following code is used to save the search data:

// Save data  
function save ( ) { var siteurl = document . getElementById ( " siteurl " ) . value ;  
     var sitename = document . getElementById ( " sitename " ) . value ;  
     localStorage . setItem ( sitename , siteurl ) ;
     alert ( " Added successfully " ) ;
 }   
      
// Find data  
function find ( ) { var search_site = document . getElementById ( " search_site " ) . value ;  
     var sitename = localStorage . getItem ( search_site ) ;  
     var find_result = document . getElementById ( " find_result " ) ;  
     find_result . innerHTML = search_site +   
       " The URL is: " + sitename ;  
 }

The complete example demonstration is as follows:

Example

<!DOCTYPE html>
<html>  
<head>  
    <meta charset="utf-8">  
    <title>Web Storage of HTML5 Local Storage</title>  
</head>  
<body>  
    <div style="border: 2px dashed #ccc;width:320px;text-align:center;">     
        <label for="sitename">Site name(key):</label>  
        <input type="text" id="sitename" name="sitename" class="text"/>  
        <br/>  
        <label for="siteurl">Website(value):</label>  
        <input type="text" id="siteurl" name="siteurl"/>  
        <br/>  
        <input type="button" onclick="save()" value="Add record"/>  
        <hr/>  
        <label for="search_phone">Enter the site name:</label>  
        <input type="text" id="search_site" name="search_site"/>  
        <input type="button" onclick="find()" value="Find a website"/>  
        <p id="find_result"><br/></p>  
    </div>  
    <br/>  
    <div id="list">  
    </div>  
    <script>
	// Load all data stored in localStorage
	loadAll(); 	
		
    //save data
    function save(){  
        var siteurl = document.getElementById("siteurl").value;  
        var sitename = document.getElementById("sitename").value;  
        localStorage.setItem(sitename, siteurl);
        alert("Added successfully");
    }
    //Find data 
    function find(){  
        var search_site = document.getElementById("search_site").value;  
        var siteurl = localStorage.getItem(search_site);  
        var find_result = document.getElementById("find_result");  
        find_result.innerHTML = search_site + "The URL is:" + siteurl;  
    }
    //Extract all objects stored in localStorage and display them on the interface
    function loadAll(){  
        var list = document.getElementById("list");  
        if(localStorage.length>0){  
            var result = "<table border='1'>";  
            result += "<tr><td>key</td><td>value</td></tr>";  
            for(var i=0;i<localStorage.length;i++){  
                var sitename = localStorage.key(i);  
                var siteurl = localStorage.getItem(sitename);  
                result += "<tr><td>"+sitename+"</td><td>"+siteurl+"</td></tr>";  
            }  
            result += "</table>";  
            list.innerHTML = result;  
        }else{  
            list.innerHTML = "Data is empty...";  
        }  
    }      
    </script>
</body>  
</html>

Next we will use JSON.stringify to store object data, JSON.stringify can convert objects into strings.

var Site = new new Object ; ...
var STR = the JSON . the stringify ( Site ) ; // convert the object to a string   

Then we use the JSON.parse method to convert the string into a JSON object:

var Site = the JSON . the parse ( STR ) ; 

JavaScript implementation code:

// Save data  
function save ( ) { var site = new Object ;
     site . keyname = document . getElementById ( " keyname " ) . value ;
     site . sitename = document . getElementById ( " sitename " ) . value ;  
     site . siteurl = document . getElementById ( "   
      siteurl " ) . value ;
     var str = JSON . stringify ( site ) ; // convert the object to a string 
    localStorage . setItem ( site . keyname , str ) ;  
     alert ( " Saved successfully " ) ;
 } // Find data    

function find ( ) { var search_site = document . getElementById ( " search_site " ) . value ;  
     var str = localStorage . getItem ( search_site ) ;  
     var find_result = document . getElementById ( " find_result " ) ;
     var site = JSON . parse ( str   
        ) ;  
     find_result . innerHTML = search_site + " The site name is: " + site . sitename + " and the URL is: " + site . siteurl ;  
 }

The complete example is as follows:

Example

<!DOCTYPE html>
<html>  
<head>  
    <meta charset="utf-8">  
    <title>Web Storage of HTML5 Local Storage</title>  
</head>  
<body>  
    <div style="border: 2px dashed #ccc;width:320px;text-align:center;">
        <label for="keyname">Alias(key):</label>  
        <input type="text" id="keyname" name="keyname" class="text"/>  
        <br/>  
        <label for="sitename">Site name:</label>  
        <input type="text" id="sitename" name="sitename" class="text"/>  
        <br/>  
        <label for="siteurl">Website:</label>  
        <input type="text" id="siteurl" name="siteurl"/>  
        <br/>  
        <input type="button" onclick="save()" value="Add record"/>  
        <hr/>  
        <label for="search_phone">Enter alias(key):</label>  
        <input type="text" id="search_site" name="search_site"/>  
        <input type="button" onclick="find()" value="Find a website"/>  
        <p id="find_result"><br/></p>  
    </div>  
    <br/>  
    <div id="list">  
    </div>  
    <script>
    //save data  
    function save(){  
        var site = new Object;
        site.keyname = document.getElementById("keyname").value;
        site.sitename = document.getElementById("sitename").value;  
        site.siteurl = document.getElementById("siteurl").value;
        var str = JSON.stringify(site); // Convert object to string
        localStorage.setItem(site.keyname,str);  
        alert("Saved successfully");
    }  
    //Find data
    function find(){  
        var search_site = document.getElementById("search_site").value;  
        var str = localStorage.getItem(search_site);  
        var find_result = document.getElementById("find_result");
        var site = JSON.parse(str);  
        find_result.innerHTML = search_site + "The site name is:" + site.sitename + ",the website is:" + site.siteurl;  
    }  
    
    //Extract all objects stored in localStorage and display them on the interface
	// Make sure that the value corresponding to the stored keyname is the conversion object, otherwise JSON.parse will report an error
    function loadAll(){  
        var list = document.getElementById("list");  
        if(localStorage.length>0){  
            var result = "<table border='1'>";  
            result += "<tr><td>Alias</td><td>Site name</td><td>URL</td></tr>";  
            for(var i=0;i<localStorage.length;i++){ 
                var keyname = localStorage.key(i);  
                var str = localStorage.getItem(keyname);  
                var site = JSON.parse(str);  
                result += "<tr><td>"+site.keyname+"</td><td>"+site.sitename+"</td><td>"+site.siteurl+"</td></tr>";  
            }  
            result += "</table>";  
            list.innerHTML = result;  
        }else{  
            list.innerHTML = "Data is empty...";  
        }  
    }  
    </script>
</body>  
</html>