HTML5 Web Storage
HTML5 web storage, a better local storage method than cookies.
What is HTML5 Web Storage?
HTML5 allows you to store user browsing data locally.
Earlier, cookies were used for local storage. However, web storage requires more security and speed. This data is not stored on the server, but is used only for user requests to the website. It can also store large amounts of data without affecting website performance.
Data exists in key/value pairs, and web page data is only accessible by that page.
Browser Support
Internet Explorer 8+, Firefox, Opera, Chrome, and Safari support Web Storage.
Note: Internet Explorer 7 and earlier versions do not support web storage.
localStorage and sessionStorage
Two objects for client-side data storage are:
localStorage - Used for long-term storage of data for the entire website, with no expiration time until manually removed.
sessionStorage - Used for temporary storage of data for the same window (or tab), with data being deleted after the window or tab is closed.
Before using web storage, check if the browser supports localStorage and sessionStorage:
if(typeof(Storage)!=="undefined")
{
// Yes! localStorage and sessionStorage support!
// Some code.....
} else {
// Sorry! No web storage support.
}
localStorage Object
Data stored in the localStorage object has no time limit. It will still be available the next day, week, or year.
Example
// Store
localStorage.setItem("sitename", "tutorialpro.org");
// Retrieve
document.getElementById("result").innerHTML = "Website name: " + localStorage.getItem("sitename");
Example explanation:
Create a localStorage key/value pair with key="sitename" and value="tutorialpro.org".
Retrieve the value of the "sitename" key and insert the data into the element with
id="result"
.
The above example can also be written as:
// Store
localStorage.sitename = "tutorialpro.org";
// Retrieve
document.getElementById("result").innerHTML = localStorage.sitename;
Remove "sitename" from localStorage:
localStorage.removeItem("sitename");
Both localStorage and sessionStorage have the same API, with common methods such as:
Save data: localStorage.setItem(key,value);
Read data: localStorage.getItem(key);
Delete one data: localStorage.removeItem(key);
Delete all data: localStorage.clear();
Get the key of a certain index: localStorage.key(index);
Tip: Key/value pairs are usually stored as strings. You can convert the format as needed.
The following example shows the number of times a user clicks a button.
The string value is converted to a number type in the code:
Example
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";
sessionStorage Object
The sessionStorage method stores data for one session. The data is deleted when the user closes the browser window.
How to create and access a sessionStorage:
Example
if (sessionStorage.clickcount)
{
sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
}
else
{
sessionStorage.clickcount=1;
}
document.getElementById("result").innerHTML="You have clicked the button " + sessionStorage.clickcount + " times in this session";
Web Storage Develop a Simple Website List Program
The website list program implements the following functions:
Can enter the website name, URL, and store it in localStorage with the website name as the key;
Find the URL based on the website name;
List all currently saved websites;
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");
}
// 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 + "'s URL is: " + sitename;
}
Complete example demonstration:
Example
<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">URL (value):</label>
<input type="text" id="siteurl" name="siteurl"/>
<br/>
<input type="button" onclick="save()" value="Add Record"/>
<hr/>
<label for="search_site">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>
The above example only demonstrates simple localStorage storage and retrieval. More often, the data we store will be more complex.
Next, we will use JSON.stringify to store object data, JSON.stringify can convert objects into strings.
var site = new Object;
...
var str = JSON.stringify(site); // Convert the object to a string
Then we use JSON.parse to convert the string back 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");
}
// 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 + "'s website name is: " + site.sitename + ", URL is: " + site.siteurl;
}
Complete example:
Example
<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">URL:</label>
<input type="text" id="siteurl" name="siteurl"/>
<br/>
<input type="button" onclick="save()" value="Add Record"/>
<hr/>
<label for="search_site">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>
Example: The loadAll
function 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 demonstration: