localStorage和sessionStorage区别

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();
 
————————————————
版权声明:本文为CSDN博主「wanf_」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_31741481/article/details/88054069

原文地址:https://www.cnblogs.com/2019gdiceboy/p/12133160.html