除了非持久化和仅作用于当前窗口之外,会话存储相对于本地存储是否有任何好处(性能,数据访问等)?
当前回答
The only difference is that localStorage has a different expiration time, sessionStorage will only be accessible while and by the window that created it is open. localStorage lasts until you delete it or the user deletes it. Lets say that you wanted to save a login username and password you would want to use sessionStorageover localStorage for security reasons (ie. another person accessing their account at a later time). But if you wanted to save a user's settings on their machine you would probably want localStorage. All in all:
localStorage—用于长期使用。 sessionStorage—当您需要存储更改的东西或临时的东西时使用
其他回答
其他几点可能有助于理解本地存储和会话存储之间的区别
Both local storage and session storage are scoped to document origin, so https://mydomain.example/ http://mydomain.example/ https://mydomain.example:8080/ All of the above URL's will not share the same storage. (Notice path of the web page does not affect the web storage) Session storage is different even for the document with same origin policy open in different tabs, so same web page open in two different tabs cannot share the same session storage. Both local and session storage are also scoped by browser vendors. So storage data saved by IE cannot be read by Chrome or FF.
晚回答,但觉得在这里补充了一些观点。
会话存储将可用于特定的选项卡,因为我们可以通过浏览器使用本地存储。两者默认都是同源的,我们也可以手动用键、值对存储值(值必须是字符串)。
一旦浏览器的选项卡(会话)关闭,那么会话存储将在该选项卡上被清除,在本地存储的情况下,我们需要显式地清除它。最大存储限制分别为5MB和10MB。
我们可以像下面这样保存和检索数据,
保存:
sessionStorage.setItem('id', noOfClicks); // localStorage.setItem('id', noOfClicks);
sessionStorage.setItem('userDetails', JSON.stringify(userDetails)); // if it's object
得到:
sessionStorage.getItem('id'); // localStorage.getItem('id');
User user = JSON.parse(sessionStorage.getItem("userDetails")) as User; // if it's object
修改:
sessionStorage.removeItem('id'); // localStorage.removeItem('id');
sessionStorage.clear(); // localStorage.clear();
p.s.: getItem()也返回数据作为字符串,我们需要将其转换为JSON格式来访问如果它是对象。
你可以阅读更多关于浏览器存储在这里。
localStorage, sessionStorage和cookie的区别 localstorage-vs-sessionstorage
sessionStorage与localStorage相同,只是它只存储一个会话的数据,并且当用户关闭创建它的浏览器窗口时,它将被删除。
sessionStorage为每个给定的源维护一个单独的存储区域,该存储区域在页面会话期间可用(只要浏览器打开,包括页面重新加载和恢复)。 localStorage做同样的事情,但是即使浏览器关闭并重新打开,它仍然存在。
我从Web存储API中获得了这个
localStorage和sessionStorage都扩展了Storage。除了sessionStorage的“非持久性”之外,它们之间没有任何区别。
也就是说,存储在localStorage中的数据将一直存在,直到显式删除为止。所做的更改将被保存,并可用于当前和将来对站点的所有访问。
对于sessionStorage,更改仅适用于每个选项卡。所做的更改将被保存,并可用于该选项卡中的当前页面,直到关闭该选项卡为止。一旦关闭,存储的数据就会被删除。
推荐文章
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有JQuery)?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 在输入type="number"时禁用webkit的旋转按钮?
- 如何在另一个元素之后添加一个元素?
- 我如何有效地解析HTML与Java?
- “ ”和“”有什么区别?
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?