2

sessionStorage详解

 1 year ago
source link: https://blog.p2hp.com/archives/8919
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

sessionStorage可以使用setItem设置、getItem获取、removeItem删除、clear清空。具体详见MDN

MDN解释

sessionStorage 属性允许你访问一个 session Storage 对象。它与 localStorage 相似,不同之处在于 localStorage 里面存储的数据没有过期时间设置,而存储在 sessionStorage 里面的数据在页面会话结束时会被清除。页面会话在浏览器打开期间一直保持,并且重新加载或恢复页面仍会保持原来的页面会话。**在新标签或窗口打开一个页面时会在顶级浏览上下文中初始化一个新的会话,**这点和 session cookies 的运行方式不同。

可以看到sessionStorage在页面会话结束时会被清除,也就是讲一个页面上的sessionStorage在页面刷新或者恢复页面的时候都不会丢失或者被清空。

那一个域名下的sessionStorage 的数据会在同一网站的多个标签页之间共享吗?要解决这个问题,使用chrome测试了一下场景。

当在一个a页面有sessionStorage时,这时新增一个标签并输入与a页面相同的url。新的标签里面打开的页面是没有另一个标签页面里面的sessionStorage时。也就是讲,新标签是新的会话。

_blank: 在a页面点击链接或者使用window.open打开与a页面相同url的标签页面时,新标签页面sessionStorage继承自之前页面的sessionStorage,但是后续两个页面的sessionStorage是单独控制的。两个页面之间并无关联

  1. 不同tab之间就算相同url,sessionStorage也是不会共享的。sessionStorage只存在于当前会话中。
  2. 使用window.open或者点击链接跳转的页面,新页面的sessionStorage会拷贝老页面的。但两者之间并无关联,还是两个会话。

https://html.spec.whatwg.org/multipage/browsers.html#top-level-browsing-context

https://liyaoli.com/2015-03-12/HTML-iframe.html

https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

https://github.com/lmk123/blog/issues/66

https://segmentfault.com/a/1190000016910121


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK