sessionStorage 属性允许你访问一个,对应当前源的 session Storage 对象。它与 localStorage 相似,不同之处在于 localStorage 里面存储的数据没有过期时间设置,而存储在 sessionStorage 里面的数据在页面会话结束时会被清除。

  1. 页面会话在浏览器打开期间一直保持,并且重新加载或恢复页面仍会保持原来的页面会话。
  2. 在新标签或窗口打开一个页面时会复制顶级浏览会话的上下文作为新会话的上下文,这点和 session cookies 的运行方式不同。
  3. 打开多个相同的URL的Tabs页面,会创建各自的sessionStorage。
  4. 关闭对应浏览器窗口(Window)/ tab,会清除对应的sessionStorage。
  5. 应该注意,存储在sessionStorage或localStorage中的数据特定于页面的协议。也就是说http://example.com 与 https://example.com的sessionStorage相互隔离。

面试有时候会被问到这类的问题,是运用中经常用到吗?网上看到的用例真的是很少。可能我的应用场景中比较少所以没有深入去研究,但想起被问过这类问题,就会激起我的好奇心去一探究竟。今天做个测试如下,如果有使用用例再做补充。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>sessionStorage</title>
</head>
<body>
	<a href="./item.html" >_blank</a>
    <a href="./item.html" target="_blank">_blank</a>
    <div onclick="location.href='./item.html'">location.href</div>
    <div onclick="open1()">window.open </div>
    <div onclick="open2()">window.open 新浏览器窗口</div>
    <script>
    	// 手动打开在新页面不保留
   		// a链接跳转新页面在新页面不保留
   		// window.open 单独打开在新的页面不保留
        // location.href 在新页面保留 (定义2)
        // window.open 打开新的浏览器窗口,在在新页面保留 (定义2)
		// 同时开两个页面,删除掉其中一个的sessionStroage,另一个是不会改变的(定义5)
        function open1() {
            window.open('./item.html')
        }
        function open2() {
            window.open('./item.html', '子页面', "width=100%")
        }
        sessionStorage.setItem('data', '11');
        

    </script>
</body>
</html>

参考:MDN

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐