The content of this lesson is to introduce web storage, which uses it to store the data of key-value pairs in the browser. It is functionally like the previous cookies, but it is better and the stored data can be larger. There are two types of web storage: local storage and session storage, which use the same implementation mechanism, except that the visibility and life cycle are different.
1. Use local storageWe use the localStorage object to access the local storage, which returns the Storage object, which is used to store the data of key-value pairs. It has the following properties and methods:
clear(): Clearly store key-value pair data;
getItem(<key>): get value through key;
key(<index>): Get the key value through the index;
length: Returns the number of key-value pairs;
removeItem(<key>): Remove the specified data through key;
setItem(<key>,<value>): Add a key-value pair. When the key-value pair of the specified key exists, the update operation is implemented;
[<key>]: Use key to get the specified value through array subscript.
The Storage object allows us to store key-value pair data in the form of strings. The key is unique, which means that when we use the setItem method to add key-value pairs, if the key value already exists, the update operation will be implemented. Let's look at the following example:
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style>
body > *{float: left;}
table{border-collapse: collapse;margin-left: 50px;}
th, td{padding: 4px;}
th{text-align: right;}
input{border: thin solid black;padding: 2px;}
label{min-width: 50px;display: inline-block;text-align: right;}
#countmsg, #buttons{margin-left: 50px;margin-top: 5px;margin-bottom: 5px;}
</style>
</head>
<body>
<div>
<div>
<label>Key:</label><input id="key" placeholder="Enter Key" /></div>
<div>
<label>Value:</label><input id="value" placeholder="Enter Value" /></div>
<div id="buttons">
<button id="add">Add</button>
<button id="clear">Clear</button>
</div>
<p id="countmsg">There are <span id="count"></span>items</p>
</div>
<table id="data">
<tr>
<th>Item Count:</th>
<td id="count">-</td>
</tr>
</table>
<script>
displayData();
var buttons = document.getElementsByTagName('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].onclick = handleButtonPress;
}
function handleButtonPress(e) {
switch (e.target.id) {
case 'add':
var key = document.getElementById('key').value;
var value = document.getElementById('value').value;
localStorage.setItem(key, value);
break;
case 'clear':
localStorage.clear();
break;
}
displayData();
}
function displayData() {
var tableElement = document.getElementById('data');
tableElement.innerHTML = '';
var itemCount = localStorage.length;
document.getElementById('count').innerHTML = itemCount;
for (var i = 0; i < itemCount; i++) {
var key = localStorage.key(i);
var val = localStorage.getItem(key);
tableElement.innerHTML += '<tr><th>' + key + ':</th><td>' + val + '</td></tr>';
}
}
</script>
</body>
</html>
Let's look at the running results :The browser cannot delete the data we created through localStorage unless the user deletes it.
2. Listen to Storage eventsThe data stored through local storage is visible to the same-original document. For example, if you open two chrome browsers to access the same URL address, the local storage created on any page is also visible to the other page. However, if you open the same URL address with another browser (such as firefox), local storage is invisible because they have different sources. The Storage event is used to listen to the changes in the storage content. Let's see which properties it contains:
key: Returns the changed key value;
oldValue: Returns the value before the change of the key value;
newValue: Returns the new value value whose key value has changed;
url: the URL address that has changed;
storageArea: Returns the changed Storage object (local storage or session storage).
Let's look at an example below:
<!DOCTYPE HTML>
<html>
<head>
<title>Storage</title>
<style>
table{border-collapse: collapse;}
th, td{padding: 4px;}
</style>
</head>
<body>
<table id="data">
<tr>
<th>key</th>
<th>oldValue</th>
<th>newValue</th>
<th>url</th>
<th>storageArea</th>
</tr>
</table>
<script>
var tableElement = document.getElementById('data');
window.onstorage = function (e) {
var row = '<tr>';
row += '<td>' + e.key + '</td>';
row += '<td>' + e.oleValue + '</td>';
row += '<td>' + e.newValue + '</td>';
row += '<td>' + e.url + '</td>';
row += '<td>' + (e.storageArea == localStorage) + '</td></tr>';
tableElement.innerHTML += row;
}
</script>
</body>
</html>
In Example 1, we add, delete and modify the storage data, and will be displayed on the Example 2 page. Example 2 runs normally in the chrome browser, firefox does not respond, and other browsers do not test it.
Running results :3. Use session storage
The session storage is the same as local storage in use, except that its accessibility is limited to the current page, and it will disappear after the page is closed. We access it through sessionStorage.
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style>
body > *{float: left;}
table{border-collapse: collapse;margin-left: 50px;}
th, td{padding: 4px;}
th{text-align: right;}
input{border: thin solid black;padding: 2px;}
label{min-width: 50px;display: inline-block;text-align: right;}
#countmsg, #buttons{margin-left: 50px;margin-top: 5px;margin-bottom: 5px;}
</style>
</head>
<body>
<div>
<div>
<label>Key:</label><input id="key" placeholder="Enter Key" /></div>
<div>
<label>Value:</label><input id="value" placeholder="Enter Value" /></div>
<div id="buttons">
<button id="add">Add</button>
<button id="clear">Clear</button>
</div>
<p id="countmsg">There are <span id="count"></span>items</p>
</div>
<table id="data">
<tr>
<th>Item Count:</th>
<td id="count">-</td>
</tr>
</table>
<iframe src="storage.html"></iframe>
<script>
displayData();
var buttons = document.getElementsByTagName("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].onclick = handleButtonPress;
}
function handleButtonPress(e) {
switch (e.target.id) {
case 'add':
var key = document.getElementById("key").value;
var value = document.getElementById("value").value;
sessionStorage.setItem(key, value);
break;
case 'clear':
sessionStorage.clear();
break;
}
displayData();
}
function displayData() {
var tableElement = document.getElementById('data');
tableElement.innerHTML = '';
var itemCount = sessionStorage.length;
document.getElementById('count').innerHTML = itemCount;
for (var i = 0; i < itemCount; i++) {
var key = sessionStorage.key(i);
var val = sessionStorage.getItem(key);
tableElement.innerHTML += "<tr><th>" + key + ":</th><td>" + val + "</td></tr>";
}
}
</script>
</body>
</html>
Running effect :If you make any changes in Example 3, the page in Example 2 will not change.
Summarize :sessionStorage is used to store data in a session locally, which can only be accessed on pages in the same session and the data will be destroyed after the session is finished. Therefore, sessionStorage is not a persistent local storage, but only a session-level storage.
localStorage is used for persistent local storage, and the data will never expire unless it is actively deleted.
The difference between web storage and cookies: The concept of Web Storage is similar to cookies, the difference is that it is designed for larger capacity storage. The size of the cookie is limited, and every time you request a new page, the cookie will be sent over, which invisibly wastes bandwidth. In addition, the cookie needs to be specified scope and cannot be called across domains. In addition, Web Storage has setItem, getItem, removeItem, clear and other methods. Unlike cookies, front-end developers need to encapsulate setCookies and getCookies themselves. Also, each domain (including subdomain) of web storage has independent storage space, and each storage space is completely independent, so it will not cause data confusion.
But cookies are also indispensable: the function of cookies is to interact with the server and exists as part of the HTTP specification, while Web Storage is only created to store data locally.
Source code download