基於'sessionStorage'與'userData'的類session存儲

Storage.js:javascript

 注意:此版本實現的存儲在符合Web存儲標準(ie8及ie8以上的版本與其餘主流瀏覽器)的狀況下與session的週期一致,但在頁面不關閉的狀況下沒有過時時間,ie7及如下版本則默認是永久保存,但能夠經過預留的方法setMaxAge(Number age)來設置有效期,設置0的話在關閉或刷新頁面時會清除緩存。html

(function initStorageClass(win){
    var inherit=function(o){
        if(o===null || o ===undefined) throw TypeError();
        if(Object.create) return Object.create(o);
        var t = typeof o;
        if(t!=='object'&&t!=='function') throw TypeError();
        function f(){}
        f.prototype=o;
        return new f();
    };
    var extend=function(a,b){
        for ( var key in b) { a[key]=b[key]; }
        return a;
    };
    var defineSubclass=function(superclass,constructor,methods,statics){
        constructor.prototype=inherit(superclass.prototype);
        constructor.prototype.constructor=constructor;
        if(methods) extend(constructor.prototype,methods);
        if(statics) extend(constructor,statics);
        return constructor;
    };
    Function.prototype.extend=function(constructor,methods,statics){
        return defineSubclass(this,constructor,methods,statics);
    };
    // 建立一個抽象類
    var AbstractStorage=function AbstractStorage(){
        throw new Error('Can\'t create abstract class instance');
    };
    // 添加抽象類的實例方法(已實現)
    extend(AbstractStorage.prototype,{
        setItem:function(k,v){
            k=encodeURIComponent(k);
            v=encodeURIComponent(v);
            this.storage.setItem(k,v);
            return this;
        },
        getItem:function(k){
            k=encodeURIComponent(k);
            return decodeURIComponent(this.storage.getItem(k));
        },
        removeItem:function(k){
            k=encodeURIComponent(k);
            this.storage.removeItem(k);
            return this;
        },
        setMaxAge:function(age){ // 爲IE的userData版本預留了設置有效期的方法
            if(isNaN(age)) throw new TypeError('userData\' max-age must be a number,but '+age+' is not a number');
            if(this.model&&this.model==='userData') {
                var now=new Date().getTime();
                var expires=now+age*1000;
                this.storage.expires=new Date(expires).toUTCString();
            } else {
                throw new Error('sessionStorage did\'t support set max-age。');
            }
            return this;
        }
    });
    var Storage=null;
    if(win.Storage) {// 實現了Web存儲標準的瀏覽器
        Storage=AbstractStorage.extend(
            function WebStorage(){
                // IE中實現了Web存儲標準的版本,在本地目錄下沒法使用sessonStorage
                if(!win.sessionStorage) {
                    throw new Error('local web is can\'t save sessionStorage');
                }
                this.model='sessionStorage';
                // 默認使用sessionStorage,也能夠本身傳入,model自行修改
                this.storage=win.sessionStorage;
            }
        );
    } else if(win.navigator.appVersion&&win.navigator.appVersion.indexOf('MSIE')>=0){
        // 不支持web存儲標準的IE瀏覽器(IE11的核心版本已和Netscape統一,IE8以上的支持web存儲標準)
        Storage=(AbstractStorage.extend(
            function IEStorage(maxAge){
                this.model='userData';
                this.maxAge=maxAge;
                this.storage=(function initUserData(t){
                    var memory = document.createElement('div');
                    memory.style.display='none';
                    //附加userData行爲
                    memory.style.behavior='url("#default#userData")';
                    document.appendChild(memory);
                    if(t.maxAge) {// 設置userData有效期,默認永久,單位毫秒
                        var now=new Date().getTime();
                        var expires=now+t.maxAge*1000;
                        memory.expires=new Date(expires).toUTCString();
                    }
                    memory.load('UserDataStorage'); //載入存儲的
                    extend(memory,{
                        setItem:function(k,v){
                            this.setAttribute(k,v);
                            this.save('UserDataStorage');
                            return this;
                        },
                        getItem:function(k){
                            return this.getAttribute(k)||null;
                        },
                        removeItem:function(k){
                            this.removeAttribute(k);
                            this.save('UserDataStorage');
                            return this;
                        }
                    });
                    return memory;
                }(this));
            }
        ));
    }
    win.IStorage=Storage;
    win.memory=new Storage()||null;// 建立一個實例對象,能夠在腳本中直接引用
}(window));

 

index.html(簡單測試):java

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="Storage.js"></script>
<script type="text/javascript">
    window.onload=function(){
        memory.setItem('test','success');
        alert(memory.getItem('test'));
    };
</script>
</head>
<body>

</body>
</html>

 

在HTML頁面中引用Storage.js文件,能夠在宿主環境中直接使用已經生成的實例memory(window.memory)。也能夠本身建立一個新實例new IStorage()web

memory.setItem('test','success');   // add
alert(memory.getItem('test'));      // select     
memory.removeItem('test');          // delete

 

適用實現了Web存儲標準的瀏覽器(Storage)與IE瀏覽器(userData),userData的生命週期請自行根據項目進行設置。瀏覽器

相關文章
相關標籤/搜索