Web Storage API 使浏览器能以一种<b><font color="#0076b3">比使用Cookie更直观</font></b>的方式存储键/值对。
sessionStorage
为每一个给定的源(given origin)维持一个独立的存储区域。<br>
<ol><li>Stores data only for a session, meaning that the data is stored until the browser (or tab) is closed.<br></li><li>Data is never transferred to the server.<br></li><li>Storage limit is larger than a cookie (at most<b><font color="#0076b3"> 5MB</font></b>).<br></li></ol>
<ol><li>A page session lasts <b>as long as the browser is open</b>, and <b>survives over page <font color="#0076b3">reloads</font> and <font color="#0076b3">restores</font></b>.<br></li><li><b>Opening a page in a new tab or window</b> creates <b>a new session</b> with the value of the top-level browsing context, which differs from how session cookies work.<br></li><li>Opening <b>multiple tabs/windows with the <font color="#0076b3">same URL</font> </b>creates sessionStorage <b>for <font color="#0076b3">each</font> tab/window</b>.<br></li><li><b>Closing a tab/window</b> <b>ends the session</b> and clears objects in sessionStorage.<br></li></ol>
Data stored in sessionStorage is <b>specific to the protocol </b>of the page. <br>In other words, <b>http://example.com</b> will have <b><font color="#0076b3">separate</font> storage </b>than <b>https://example.com</b>.<br>
localStorage
与 sessionStorage 同样的功能,但是在浏览器关闭然后重新打开后数据仍然存在。<br>
<b><font color="#0076b3">5M</font></b>左右,各浏览器的存储空间有差异。
封装方法设置失效时间
const myLocalStorage = {<br> set(key, data, time) {<br> let obj = {<br> data,<br><b> createTime: Date.now()</b>,<br><b> lifeTime: time || 1000 * 60 * 60</b> //默认设置过期时间一个小时<br> };<br> localStorage.setItem(key, JSON.stringify(obj));<br> },<br> get(key) {<br> let obj = JSON.parse(localStorage.getItem(key));<br> let {data,createTime,lifeTime}=obj<br> let getTime = Date.now();<br><b> if (getTime - createTime >= lifeTime) {<br> localStorage.removeItem(key);<br> return null;</b><br> } else {<br> return data;<br> }<br> }<br>};<br>