JavaScript sessionStorage使用

说明

将数据保存在 当前会话 中,可以使用 sessionStorage, 该数据对象 临时 保存同一窗口(或标签页) 的数据,在 关闭 窗口或标签页之后将会 删除这些数据

应用场景

使用 vue 这类框架实现 单页面应用 时,使用 sessionStorage 比较合理

有坑-多页面应用

多页面应用 中,不要使用

多页面应用可以共享

1.html 页面中,通过 超链接open() 函数,打开 2.html,那么 1.html2.html 可以共享 sessionStorage 中的数据

多页面应用 不共享

通过地址栏访问 1.html2.html,那么 1.html2.html 不会共享 sessionStorage 中的数据

使用

存储

sessionStorage.setItem("key", value);

读取

var name=sessionStorage.getItem("key")

例子

一般在 单页面应用 中使用

<script>
//存储
sessionStorage.setItem("name", "李雷");

//读取
var name=sessionStorage.getItem("name")
console.log(name)

</script>

原文出处:https://malaoshi.top/show_1IX2nzghuUmA.html