(function($){ var cookieexpiretime = 1209600; // cookie项过期时间 2周 $.session = { _id: null, _cookiecache: undefined, _init: function() { //if (!window.name) { // window.name = math.random(); //} //this._id = window.name; // 如果id设置为动态,会导致浏览器不断生成cookie,进而导致取值有问题 this._id = 'sessionid'; this._initcache(); // see if we've changed protcols var matches = (new regexp(this._generateprefix() + "=([^;]+);")).exec(document.cookie); if (matches && document.location.protocol !== matches[1]) { this._clearsession(); for (var key in this._cookiecache) { try { window.sessionstorage.setitem(key, this._cookiecache[key]); } catch (e) {}; } } document.cookie = this._generateprefix() + "=" + document.location.protocol + ';path=/;expires=' + (new date((new date).gettime() + 28800000 + cookieexpiretime)).toutcstring(); // 28800000 含义:世界时间+8天=北京时间 }, _generateprefix: function() { return '__session:' + this._id + ':'; }, _initcache: function() { var cookies = document.cookie.split(';'); this._cookiecache = {}; for (var i in cookies) { var kv = cookies[i].split('='); if ((new regexp(this._generateprefix() + '.+')).test(kv[0]) && kv[1]) { this._cookiecache[kv[0].split(':', 3)[2]] = kv[1]; } } }, _setfallback: function(key, value, onceonly) { var cookie = this._generateprefix() + key + "=" + value + ";path=/"; if (onceonly) { // 只一次设置项,为其添加过期时间,过期自动删除 cookie += ";expires=" + (new date(date.now() + 28800000 + cookieexpiretime)).toutcstring(); } document.cookie = cookie; this._cookiecache[key] = value; return this; }, _getfallback: function(key) { if (!this._cookiecache) { this._initcache(); } return this._cookiecache[key]; }, _clearfallback: function() { for (var i in this._cookiecache) { document.cookie = this._generateprefix() + i + '=;path=/;expires=thu, 01 jan 1970 00:00:01 gmt;'; } this._cookiecache = {}; }, _deletefallback: function(key) { document.cookie = this._generateprefix() + key + '=;path=/;expires=thu, 01 jan 1970 00:00:01 gmt;'; // 把有效时间设置为过期 delete this._cookiecache[key]; }, get: function(key) { return window.sessionstorage.getitem(key) || this._getfallback(key); }, set: function(key, value, onceonly) { try { window.sessionstorage.setitem(key, value); } catch (e) {} this._setfallback(key, value, onceonly || false); return this; }, 'delete': function(key){ return this.remove(key); }, remove: function(key) { try { window.sessionstorage.removeitem(key); } catch (e) {}; this._deletefallback(key); return this; }, _clearsession: function() { try { window.sessionstorage.clear(); } catch (e) { for (var i in window.sessionstorage) { window.sessionstorage.removeitem(i); } } }, clear: function() { this._clearsession(); this._clearfallback(); return this; } }; $.session._init(); })(jquery);