我正在构建一个表单,需要将数据存储在HTML5的
sessionStorage
中。我不知道sessionStorage
何时过期。有人能告诉我sessionStorage
的过期时间吗?sessionStorage
中。我不知道sessionStorage
何时过期。有人能告诉我sessionStorage
的过期时间吗?我知道这个问题很久了,但如果有其他人碰巧发现并发现它有用,我会发布我的答案。你可以通过类似于以下内容来模拟sessionStorage
或localStorage
的过期时间:
//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));
如果您不希望此会话对象明文存储,可以使用类似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');
}
});
如果您不希望用户在标签页或浏览器关闭后仍保持登录状态,请使用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))
}
sessionStorage
在关闭浏览器时并不会过期,可以跨越多个浏览器会话。如果你关闭了浏览器并保存了标签页,或者浏览器崩溃并在重新启动时恢复了标签页,它将被视为同一次会话。请注意这一行:“浏览上下文的生命周期可能与实际用户代理进程的生命周期无关,因为用户代理可能支持在重新启动后恢复会话”。 - Useless CodesessionStorage
也会经受住重载的考验。 - Useless Code