客户端JS会话库 [英] Client-side JS session library
问题描述
我正在寻找一个用于存储会话变量的客户端JS库。
I'm looking for a client-side JS library to store session variables.
我想要一个支持其他存储介质的库,例如Cookie,但可以使用其他技术的后备功能。
例如,我找到了这个(但是最近一次更新是在2009年):
http://code.google.com/p/sessionstorage/
I'd like a library that supports alternative storage medium, e.g. cookies when available with fallback on other techniques. For instance, I found this one (but the last update is in 2009): http://code.google.com/p/sessionstorage/
我对安全性不感兴趣(除了应用程序之间的一些数据隔离之外) ),因为我不会存储敏感数据。
I'm not interested in security (apart a bit of data isolation among applications), as I'm not going to store sensitive data.
举一个用例的例子,我想显示一条消息: Chrome用户?下载该应用对于chrome用户,我想保持会话状态,以避免再次向同一用户显示该消息。我不希望服务器端会话启用缓存,因此我必须能够为不同的用户提供完全相同的页面。
To give an example of use case, I want to display a message "Chrome user? Download the app" for chrome users, and I'd like to maintain a status in session to avoid displaying the message again to the same user. I don't want server-side sessions as I have caching enabled, so I must be able to serve the exact same page to different users.
推荐答案
您可以使用 localStorage
(如果没有),然后使用cookie(或您认为有的任何东西):
You can use localStorage
if available, and if it's not, then using cookies (or whatever you feel to):
var appToken = createToken();
try {
if (localStorage.getItem) {
localStorage.downloadAppAlert = appToken;
} else {
setCookie('downloadAppAlert', appToken, 10); // name, a string value, num. of days
}
} catch(e) {
console.log(e);
}
然后,您可以使用某些功能来设置Cookie-即,我只是在 w3schools 中找到:
Then you can use some function to set your cookies - i.e. this one i just found in w3schools:
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
要以其名称检索cookie值- downloadAppAlert 在示例中-您可以使用w3schools链接上的那个或类似的东西:
To retrieve a cookie value by it's name - downloadAppAlert in the example - you can use the one on the w3schools link or something like this:
function readCookie(name) {
var nameEQ = name + '=';
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
此外,还可以检索上先前设置的项目您只需:
Also, to retrieve a previously setted item on the localStorage
you simply:
var appToken = localStorage.getItem('downloadAppAlert');
编辑:抱歉,我急着忘了说什么 createToken()
可以。它应该是随机的字母数字生成器函数。您可以找到很多关于SO的信息,例如:
Sorry, with the hurries i forgot to mention what createToken()
does. It is supposed to be a random alphanumeric generator function. You can find plenty on SO, like:
这篇关于客户端JS会话库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!