The content of this lesson is to introduce web storage, which is used to store key-value pair data in the browser. It functions like the previous cookies, but it is better and can store larger data. There are two types of web storage: local storage and session storage. They use the same implementation mechanism, but have different visibility and life cycles.
1. Use local storage
We use the localStorage object to access local storage. It returns the Storage object. Storage is used to store key-value pair data. It has the following properties and methods:
clear(): Clear the stored key-value pair data;
getItem(): Get the value through key;
key(): Get the key value through index;
length: Returns the number of key-value pairs;
removeItem(): Removes the specified data by key;
setItem(,): Adds a key-value pair, When the key-value pair of the specified key exists, the update operation is implemented;
[]: Use key to obtain the specified value through array subscripting.
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 a key-value pair, if the key value already exists, it will be updated. operation. Let’s look at the following example:
< !DOCTYPE HTML>
Example <script> <br>displayData(); <br>var buttons = document.getElementsByTagName('button'); <br>for (var i = 0; i < buttons.length; i ) { <br />buttons[i].onclick = handleButtonPress; <br />} <br />function handleButtonPress(e) { <br />switch (e.target.id) { <br />case 'add': <br />var key = document.getElementById('key').value; <br />var value = document.getElementById('value').value; <br />localStorage.setItem(key, value); <br />break; <br />case 'clear': <br />localStorage.clear(); <br />break; <br />} <br />displayData(); <br />} <br />function displayData() { <br />var tableElement = document.getElementById ('data'); <br />tableElement.innerHTML = ''; <br />var itemCount = localStorage.length; <br />document.getElementById('count').innerHTML = itemCount; <br />for (var i = 0; i < itemCount; i ) { <br />var key = localStorage.key(i); <br />var val = localStorage.getItem(key); <br />tableElement.innerHTML = '<tr>< th>' key ':</th><td>' val '</td></tr>'; <br>} <br>} <br></script>
< ;/body>
Let’s take a look at the running results:
The browser cannot delete the data we created through localStorage unless the user deletes it.
2. Listen to Storage events Data stored through local storage is visible to documents from the same source. For example, if you open two chrome browsers to access the same URL address, on any page The local storage created on the page is also visible to another page. However, if you use another browser (such as Firefox) to open the same URL address, the local storage will not be visible because they have different sources. The Storage event is used to monitor changes in the storage content. Let’s see what attributes it contains:
key: Returns the changed key value;
oldValue: Returns the value before the key value was changed;
newValue: Returns the new value of the changed key value;
url: The changed url address;
storageArea: Returns the changed Storage object (whether it is local storage or session storage).
Let’s look at an example below:
Storage
key |
oldValue |
newValue |
url |
storageArea |
<script> <br>var tableElement = document.getElementById('data'); <br>window.onstorage = function (e) { <br>var row = '<tr>'; <br>row = '<td>' e.key '< ;/td>'; <br>row = '<td>' e.oleValue '</td>'; <br>row = '<td>' e.newValue '</td>'; <br>row = '<td>' e.url '</td>'; <br>row = '<td>' (e.storageArea == localStorage) '</td></ tr>'; <br>tableElement.innerHTML = row; <br>} <br></script>
The data we added, deleted, and modified storage in Example 1 will be displayed on the Example 2 page. Example 2 runs normally in Chrome browser, but Firefox does not respond. Other browsers have not been tested.
Run result:
3. Use session storage
Session storage is used the same as local storage, except that its accessibility is limited to the current page, and it will disappear after the page is closed. We access it through sessionStorage.
Example <script> <br>displayData(); <br>var buttons = document.getElementsByTagName("button"); <br>for (var i = 0; i < buttons.length; i ) { <br>buttons[i].onclick = handleButtonPress; <br>} <br>function handleButtonPress(e) { <br>switch (e.target.id) { <br>case 'add': <br>var key = document.getElementById("key").value; <br>var value = document.getElementById("value").value; <br>sessionStorage.setItem(key, value); <br>break; <br>case 'clear': <br>sessionStorage.clear(); <br>break; <br>} <br>displayData(); <br>} <br>function displayData() { <br>var tableElement = document.getElementById('data'); <br>tableElement.innerHTML = ''; <br>var itemCount = sessionStorage.length; <br>document.getElementById('count').innerHTML = itemCount; <br>for (var i = 0; i < itemCount; i ) { <br>var key = sessionStorage.key(i); <br>var val = sessionStorage.getItem(key); <br>tableElement.innerHTML = "<tr><th>" key ":</th><td>" val "</td></tr>"; <br>} <br>} <br></script>
运行效果:
你在例3中做任何修改,例2的页面不会发生任何改变。
总结:
sessionStorage用于本地存储一个会话(session)中的数据,这些数据只有在同一个会话中的页面才能访问并且当会话结束后数据也随之销毁。因此sessionStorage不是一种持久化的本地存储,仅仅是会话级别的存储。
localStorage用于持久化的本地存储,除非主动删除数据,否则数据是永远不会过期的。
web storage和cookie的区别:Web Storage的概念和cookie相似,区别是它是为了更大容量存储设计的。Cookie的大小是受限的,并且每次你请求一个新的页面的时候Cookie都会被发送过去,这样无形中浪费了带宽,另外cookie还需要指定作用域,不可以跨域调用。除此之外,Web Storage拥有setItem,getItem,removeItem,clear等方法,不像cookie需要前端开发者自己封装setCookie,getCookie。还有,web storage每个域(包括子域)有独立的存储空间,各个存储空间是完全独立的,因此不会造成数据混乱。
但是Cookie也是不可以或缺的:Cookie的作用是与服务器进行交互,作为HTTP规范的一部分而存在 ,而Web Storage仅仅是为了在本地“存储”数据而生。
源码下载