简体   繁体   中英

Client-side JS session library

I'm looking for a client-side JS library to store session variables.

I'd like a library that supports alternative storage medium, eg 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.

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.

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);
}

Then you can use some function to set your cookies - ie 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;
}

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');

EDIT: 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:

Random alpha-numeric string in JavaScript?

Generate random string/characters in JavaScript

Generating (pseudo)random alpha-numeric strings

使用mozilla的node-client-sessions( https://github.com/mozilla/node-client-sessions )。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM