html5 sessionStorage util

 

  

/**
 * Created by 13352 on 2018/7/5.
 */
define(function() {
    var session = {
        _id: null,
        _cookieCache: undefined,
        _init: function() {
            if (!window.name) {
                window.name = Math.random();
            }
            this._id = window.name;
            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 {
                        if (this._cookieCache.hasOwnProperty(key)) {
                            window.sessionStorage.setItem(key, this._cookieCache[key]);
                        }
                    } catch (e) {
                        console.error(e);
                    }
                }
            }
            document.cookie = this._generatePrefix() + '=' + document.location.protocol + ';path=/;expires=' + (new Date((new Date).getTime() + 120000)).toUTCString();
        },
        _generatePrefix: function() {
            return '__session:' + this._id + ':';
        },
        _initCache: function() {
            var cookies = document.cookie.split(';');
            this._cookieCache = {};
            var self = this;
            cookies.forEach(function(cookie) {
                var kv = cookie.split('=');
                if ((new RegExp(self._generatePrefix() + '.+')).test(kv[0]) && kv[1]) {
                    self._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() + 120000)).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;
        },
        del: function(key) {
            return this.remove(key);
        },
        remove: function(key) {
            try {
                window.sessionStorage.removeItem(key);
            } catch (e) {
                console.error(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();

    return session;
});

  

  config.js

// https://requirejs.org/docs/release/2.1.11/comments/require.js
// https://requirejs.org/docs/release/2.1.11/minified/require.js
require.config({
    paths : {
        "jquery-1.10.2" : "../assets/js/jquery",
        "jquery-ui": "../assets/jqui/jquery-ui",
        // "jquery": "../assets/bootstrap/js/jquery-3.3.1.min",
        "jquery": "../assets/ckeditor/js/jquery-3.2.1",
        "ckeditor-core": "../assets/ckeditor/ckeditor",
        'ckeditor-jquery': "../assets/ckeditor/adapters/jquery",
        "jquery-cookie": "../assets/js/jquery.cookie",
        "bootstrap": "../assets/bootstrap/js/bootstrap",
        "alert": "js/lib/alert",
        "supersized": "../assets/js/login/supersized.3.2.7",
        "url-param": "js/util/getUrlParam",
        'image-preview': 'js/util/preview',
        'cropbox': "../assets/cropbox/cropbox",
        'session': "js/util/session"
    },
    shim: {
        'ckeditor-jquery':{deps:['jquery','ckeditor-core']},
        'jquery-cookie': {deps: ['jquery']},
        'bootstrap': {deps: ['jquery']},
        'jquery-ui':{deps: ['jquery']},
        'supersized': {deps: ['jquery']},
        'cropbox': {deps: ['jquery']}
    }
});

  

 

  Usage:

require(['session'], function(session) {
    session.set('schoolName', '许昌市家里蹲大学');
    var schoolName = session.get('schoolName');
    console.log(schoolName);  // 许昌市家里蹲大学

    session.set('a', JSON.stringify({a:1,b:2}));
    var a= session.get('a');
    console.log(a);  // {"a":1,"b":2}
});

  

 

posted @ 2018-07-05 10:04  zhanghui_ming  阅读(180)  评论(0编辑  收藏  举报