Jit*_*iya 41 javascript html5 storage
我正在构建一个表单,我必须将数据存储在html5中,sessionStorage我不知道sessionStorage过期的地方.任何人都可以告诉我有关的到期时间sessionStorage
Pet*_*sen 59
它与您的浏览器会话一起生存和死亡,并且不在标签之间共享.它不会自动失效.因此,如果您从未关闭浏览器,它永远不会过期.
因此,当关闭选项卡/窗口时,数据将丢失.
每个会话存储区域允许5mb存储空间(在某些浏览器中为10mb).其中cookie只允许4kb(或某些浏览器中更多).然而,Cookie具有设定的到期日期.
正如克里斯托夫在评论中写道的那样,本地存储永不过期.它也在标签之间共享,与sessionstorage(5mb)的大小相同.
小智 18
我知道这个问题已经很老了,但如果其他人偶然发现这个问题并发现它有用,我会发布我的答案.您可以使用以下内容进行模拟sessionStorage或locaStorage过期:
//In your login logic or whatever
var expires = new Date(year, month, day, hours, minutes, seconds, milliseconds);
var sessionObject = {
expiresAt: expires,
someOtherSessionData: {
username: ''
}
}
sessionStorage.setItem('sessionObject', JSON.stringify(sessionObject));
Run Code Online (Sandbox Code Playgroud)
如果您不希望此会话对象清楚,您还可以使用类似http://bitwiseshiftleft.github.io/sjcl/的内容加密此对象.
在每个页面加载时,您可以检查是否已过期sessionStorage或localStorage过期:
$(document).ready(function(){
var currentDate = new Date();
var sessionObject = JSON.parse(sessionStorage.getItem('sessionObject'));
var expirationDate = sessionObject.expiresAt;
if(Date.parse(currentDate) < Date.parse(expirationDate)) {
//normal application behaviour => session is not expired
var someAppVariable = sessionObject.someOtherSessionData.etc;
} else {
//redirect users to login page or whatever logic you have in your app
//and remove the sessionStorage because it will be set again by previous logic
sessionStorage.removeItem('sessionObject');
console.log('session expired');
}
});
Run Code Online (Sandbox Code Playgroud)
如果您不希望在选项卡或浏览器关闭使用后保持用户登录,sessionStorage则应根据需要使用localStorage和操作它.
我希望有人会觉得这很有帮助.
您可以使用以下内容添加某种过期机制:
// get from session (if the value expired it is destroyed)
function sessionGet(key) {
let stringValue = window.sessionStorage.getItem(key)
if (stringValue !== null) {
let value = JSON.parse(stringValue)
let expirationDate = new Date(value.expirationDate)
if (expirationDate > new Date()) {
return value.value
} else {
window.sessionStorage.removeItem(key)
}
}
return null
}
// add into session
function sessionSet(key, value, expirationInMin = 10) {
let expirationDate = new Date(new Date().getTime() + (60000 * expirationInMin))
let newValue = {
value: value,
expirationDate: expirationDate.toISOString()
}
window.sessionStorage.setItem(key, JSON.stringify(newValue))
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
50497 次 |
| 最近记录: |