目录
1. 浏览器兼容性
2. localStorage
3. sessionStorage
Web Storage API 提供了存储机制,通过该机制,浏览器可以安全地存储键值对,比使用 cookie 更加直观。Web Storage 包含如下两种机制:
sessionStoragelocalStorage1. 浏览器兼容性
2. localStorage
localStorage 存储的数据是永久性的,除非通过 JavaScript 删除或者用户清除浏览器缓存,否则数据将一直保留在用户的电脑上,永不过期;localStorage 的作用域受同源策略限制(协议、主机名、端口),同源的文档间共享同样的localStorage数据;localStorage 的作用域也受浏览器厂商限制,Chrome 与 Firefox 中的 localStorage 无法共享; localStorage 中只能存储字符串!!!!支持 storage 存储事件;API:
localStorage.setItem('myCat', 'Tom'); // 增加一个 localStorage 项 let cat = localStorage.getItem('myCat'); // 读取 localStorage 项 localStorage.removeItem('myCat'); // 移除 localStorage 项 localStorage.clear(); // 清空所有 localStorage 项示例:
index.html:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width"> <title>Web Storage API example</title> <link href='https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Bitter|Ubuntu+Mono' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="style.css"> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <div class="wrapper"> <h1>Web storage</h1> <p>This example is designed to demonstrate usage of the <a href="http://dev.w3.org/html5/webstorage/">W3C Web Storage API</a>. It should work as far back as IE8. Choose custom background colours, logos and fonts from the below drop down menus, then try closing and reopening the page — you will find that your choices are remembered, as they are stored using Web Storage. You can also visit the <a href="event.html" target="_blank">storage event output</a> (opens in new tab). Open this, change some values in the index page, then look at the events page — you'll see the storage changes reported.</p> <form> <div> <label for="bgcolor">Choose background color:</label> <input class="color" id="bgcolor" value="FF0000"> </div> <div> <label for="font">Choose font style:</label> <select id="font"> <option value="'Open Sans Condensed', sans-serif" selected>Sans-serif</option> <option value="'Bitter', serif">Serif</option> <option value="'Ubuntu Mono'">Monospace</option> </select> </div> <div> <label for="image">Choose image:</label> <select id="image"> <option value="images/firefoxos.png" selected>Firefox</option> <option value="images/crocodile.png">Crocodile</option> <option value="images/tortoise.png">Tortoise</option> </select> </div> </form> <footer></footer> <img src="images/firefoxos.png"> </div> </body> <script src="jscolor/jscolor.js"></script> <script src="main.js"></script> </html>main.js:
var htmlElem = document.querySelector('html'); var pElem = document.querySelector('p'); var imgElem = document.querySelector('img'); var bgcolorForm = document.getElementById('bgcolor'); var fontForm = document.getElementById('font'); var imageForm = document.getElementById('image'); if(!localStorage.getItem('bgcolor')) { populateStorage(); } else { setStyles(); } function populateStorage() { localStorage.setItem('bgcolor', document.getElementById('bgcolor').value); localStorage.setItem('font', document.getElementById('font').value); localStorage.setItem('image', document.getElementById('image').value); setStyles(); } function setStyles() { var currentColor = localStorage.getItem('bgcolor'); var currentFont = localStorage.getItem('font'); var currentImage = localStorage.getItem('image'); document.getElementById('bgcolor').value = currentColor; document.getElementById('font').value = currentFont; document.getElementById('image').value = currentImage; htmlElem.style.backgroundColor = '#' + currentColor; pElem.style.fontFamily = currentFont; imgElem.setAttribute('src', currentImage); } bgcolorForm.onchange = populateStorage; fontForm.onchange = populateStorage; imageForm.onchange = populateStorage;3. sessionStorage
sessionStorage 的工作方式和 localStorage 很接近,不同之处在于储存数据的有效期与作用域;
A page session lasts as long as the browser is open, and survives over page reloads and restores。浏览器(或选项卡)刷新时,不会引起 sessionStorage 销毁;Closing a tab/window ends the session and clears objects in sessionStorage.会在浏览器(或选项卡)被关闭时销毁。The sessionStorage property accesses a session Storage object for the current origin.同源策略是根本。 Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window.如果手动打开多个Tab或窗口,即便同源,也是不同的 sessionStorage。 Opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.<a href="同源页面" target="_self">跳转</a><a href="同源页面" target="_blank">跳转</a>window.location.href = '同源页面'window.location.replace('同源页面')window.open('同源页面')同一浏览器Tab页下的两个同源iframe共享 sessionStorage 数据
示例:sessionStorage 存储应用状态;
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> </style> </head> <body> Counter: <input id="counter" value="0" disabled /> <button onclick="add()">+</button> <button onclick="sub()">-</button> <hr/> <button onclick="windowOpenNew()">window.open</button> <a href="./html.html" target="_self">href</a> <script> function windowOpenNew(){ window.open("./html.html"); } </script> <script> function add(){ const o = document.getElementById("counter"); o.value = Number(o.value)+1; save(o.value); } function sub(){ const o = document.getElementById("counter"); o.value = Number(o.value)+1; save(o.value); } function save(v){ sessionStorage.setItem("counter", v); } function restore(){ const o = document.getElementById("counter"); o.value = sessionStorage.getItem("counter"); } window.onload = function(){ restore(); } </script> </body> </html> ---来自腾讯云社区的---WEBJ2EE
微信扫一扫打赏
支付宝扫一扫打赏