localStorage 和 sessionStorage 一样都是用来存储客户端临时信息的对象.
他们均只能存储字符串类型的对象 (虽然规范中可以存储其他原生类型的对象, 但是目前为止没有浏览器对其进行实现).
localStorage 生命周期是永久, 这意味着除非用户显示在浏览器提供的 UI 上清除 localStorage 信息, 否则这些信息将永远存在.
sessionStorage 生命周期为当前窗口或标签页, 一旦窗口或标签页被永久关闭了, 那么所有通过 sessionStorage 存储的数据也就被清空了.
不同浏览器无法共享 localStorage 或 sessionStorage 中的信息. 相同浏览器的不同页面间可以共享相同的 localStorage(页面属于相同域名和端口), 但是不同页面或标签页间无法共享 sessionStorage 的信息. 这里需要注意的是, 页面及标 签页仅指顶级窗口, 如果一个标签页包含多个 iframe 标签且他们属于同源页面, 那么他们之间是可以共享 sessionStorage 的.
同源的判断规则:
URL"http://www.example.com/dir/page.html" 的对比.
对比 URL | 结果 | 结果 |
---|---|---|
http://www.example.com/dir/page2.html | 同源 | 相同的协议,主机,端口 |
http://www.example.com/dir2/other.html | 同源 | 相同的协议,主机,端口 |
http://username:password@www.example.com/dir2/other.html | 同源 | 相同的协议,主机,端口 |
http://www.example.com:81/dir/other.html | 不同源 | 相同的协议,主机,端口不同 |
https://www.example.com/dir/other.html | 不同源 | 协议不同 |
http://en.example.com/dir/other.html | 不同源 | 不同主机 |
http://example.com/dir/other.html | 不同源 | 不同主机 (需要精确匹配) |
http://v2.www.example.com/dir/other.html | 不同源 | 不同主机 (需要精确匹配) |
http://www.example.com:80/dir/other.html | 看情况 | 端口明确,依赖浏览器实现 |
不像其他浏览器, IE 在计算源的时候没有包括端口.
JSON 对象提供的 parse 和 stringify 将其他数据类型转化成字符串, 再存储到 storage 中就可以了
操作的方式:
存:
- var obj = {
- "name":"xiaoming","age":"16"
- }
- localStorage.setItem("userInfo",JSON.stringify(obj));
取:
var user = JSON.parse(localStorage.getItem("userInfo"))
删除:
localStorage.remove("userInfo);
清空:
localStorage.clear();
更多 web 开发 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/qa/frontend/20073.html