English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML5 Client-side storage

HTML5 Client-side storage, a better local storage method than cookies. Using HTML5User browsing data can be stored locally.

What is HTML5 Web client storage?

Using HTML5User browsing data can be stored locally.

Earlier, local storage used to be cookies. However, web storage requires greater security and speed. These data are not stored on the server, but are used only for user requests for website data. It can also store a large amount of data without affecting the performance of the website.

Data is stored with keys/Value pair exists, the data of web pages only allows access and use by the same web page.

Browser Support

Internet Explorer 8+, Firefox, Opera, Chrome, and Safari support web storage.

Note: Internet Explorer 7 And earlier IE versions do not support web storage.

localStorage and sessionStorage 

The two objects used to store client-side data are:

  • localStorage - Used to save the data of the entire website permanently, and the saved data does not have an expiration time until manually removed.

  • sessionStorage - Used to temporarily save data for the same window (or tab), which will be deleted after closing the window or tab.

Before using web storage, you should check if the browser supports localStorage and sessionStorage:

if(typeof(Storage)!=="undefined")
{
    // Yes! localStorage and sessionStorage objects are supported!
    // Some code.....
}
    // Sorry! Web storage is not supported.
}

localStorage object

The data stored in the localStorage object has no time limit. The data will still be available the next day, the next week, or even a year later.

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>Basic Tutorial Website(oldtoolbag.com)</title> 
</head>
<body>
<div id="result"></div>
<script>
if(typeof(Storage)!=="undefined")
{
  localStorage.sitename = "Basic Tutorial Website";
  document.getElementById("result").innerHTML = "Website Name:"; + localStorage.sitename;
}
else
{
  document.getElementById("result").innerHTML="Sorry, your browser does not support web storage.";
}
</script>
</body>
</html>
Test and See ‹/›

Example Analysis:

  • Create a localStorage key using key="sitename" and value="Basic Tutorial Website"./Value pair.

  • Retrieve the value with the key "sitename" and then insert the data into the element with id="result".

The above example can also be written like this:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>Basic Tutorial Website(oldtoolbag.com)</title> 
</head>
<body>
<script>
// Store
localStorage.sitename = "Basic Tutorial Website";
// Search
document.getElementById("result").innerHTML = localStorage.sitename;
</script>
</body>
</html>
Test and See ‹/›

Remove "sitename" from localStorage:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>Basic Tutorial Website(oldtoolbag.com)</title> 
</head>
<body>
localStorage.removeItem("sitename");
</body>
</html>
Test and See ‹/›

Whether it is localStorage or sessionStorage, the available APIs are the same, and the commonly used ones are as follows (take localStorage as an example):

  • Save data: localStorage.setItem(key,value);

  • Read data: localStorage.getItem(key);

  • Delete individual data: localStorage.removeItem(key);

  • Delete all data: localStorage.clear();

  • Get a key by index: localStorage.key(index);

Tip: Key/Values are usually stored as strings, and you can convert the format as needed.

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

String values in the code are converted to numeric type:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>Basic Tutorial Website(oldtoolbag.com)</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">Click Me! </button></p>
<div id="result"></div>
<p>Click the button to view the increase of the counter.</p>
<p>Closing the browser tab(or window), and then reopening this page will continue counting the counter(not reset).</p>
</body>
</html>
Test and See ‹/›

sessionStorage object

The sessionStorage method is used for data storage during a session. The data will be deleted when the user closes the browser window.

How to create and access a sessionStorage:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>Basic Tutorial Website(oldtoolbag.com)</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="In this session you have clicked the button" + 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">Click Me! </button></p>
<div id="result"></div>
<p>Click the button to view the increase of the counter.</p>
<p>Closing the browser tab (or window) and reopening this page will reset the counter.</p>
</body>
</html>
Test and See ‹/›

Develop a simple website list program using Web Storage

The website list program implements the following functions:

  • You can enter the website name and website address, and store them in localStorage with the website name as the key;

  • Find the website address based on the website name;

  • List all websites currently saved;

The following code is used to save and find data:

save() and find() Methods

//Save data  
function save(){  
    var siteurl = document.getElementById("siteurl").value;  
    var sitename = document.getElementById("sitename").value;  
    localStorage.setItem(sitename, siteurl);
    alert("Added successfully");
}
//Search 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 + "'s website is:" + sitename;  
}

A complete example is demonstrated as follows:

<!DOCTYPE html>
<html>  
<head>  
    <meta charset="utf-8">  
    <title>HTML5Local Storage for Web Storage Chapter</title>  
</head>  
<body>  
    <div style="border: 2px dashed #ccc;width:320px;text-align:center;">     
        <label for="sitename">Website name(key): </label>  
        <input type="text" id="sitename" name="sitename" class="text"/>}}  
        <br/>}}  
        <label for="siteurl">Website address(value): </label>  
        <input type="text" id="siteurl" name="siteurl"/>}}  
        <br/>}}  
        <input type="button" onclick="save()" value="Add Record"/>}}  
        <hr/>}}  
        <label for="search_phone">Enter website name: </label>  
        <input type="text" id="search_site" name="search_site"/>}}  
        <input type="button" onclick="find()" value="Find 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");
    }
    //Search 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 + "'s website 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;  
        }  
            list.innerHTML = "No data...";  
        }  
    }      
    </script>
</body>  
</html>
Test and See ‹/›

Screenshot of Implementation Effect:

The above example only demonstrates simple localStorage storage and search, in more cases, the data we store will be more complex.

Next, we will use JSON.stringify to store object data, as JSON.stringify can convert an object to a string.

var site = new Object;
...
var str = JSON.stringify(site); // Convert the object to a string

After that, we use the JSON.parse method to convert the string to a JSON object:

var site = JSON.parse(str);

JavaScript Implementation Code:

save() and find() Methods

//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");
}  
//Search 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 website name is:" + site.sitename + "Website URL is:" + site.siteurl;  
}

Complete Example Below:

<!DOCTYPE html>
<html>  
<head>  
    <meta charset="utf-8">  
    <title>HTML5Local Storage for Web Storage Chapter</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">Website Name: </label>  
        <input type="text" id="sitename" name="sitename" class="text"/>}}  
        <br/>}}  
        <label for="siteurl">Website URL: </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 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 the object to a string
        localStorage.setItem(site.keyname,str);  
        alert("Saved successfully");
    }  
    //Search 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 website name is:" + site.sitename + "Website URL is:" + site.siteurl;  
    }  
    
    //Extract all objects stored in localStorage and display them on the interface
    // Ensure that the value corresponding to the stored keyname is a 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>Website Name</td><td>Website 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;  
        }  
            list.innerHTML = "Data is empty...";  
        }  
    }  
    </script>
</body>  
</html>
Test and See ‹/›

The loadAll in the example outputs all stored data. You need to ensure that the data stored in localStorage is in JSON format, otherwise JSON.parse(str) will throw an error.

Output Result Demonstration: