javascript製作的cookie封裝及使用指南,javascriptcookie

來源:互聯網
上載者:User

javascript製作的cookie封裝及使用指南,javascriptcookie

一、前言

之前使用cookie,都是document.cookie的形式去操作,相容性雖好,但是麻煩。個人又是個比較喜歡造輪子的人,所以針對cookie,封裝了個工具類。很長時間以來,我都喜歡寫代碼,而不太喜歡文字總結,也不太喜歡寫些零碎的東西,看來得改。

二、思路

(1)如何封裝,封裝成啥樣

如何封裝:就是使用原生的js封裝成工具,那樣到哪裡都能能用。針對document.cookie封裝是最好的方式,所有的操作都基於document.cookie。

封裝成啥樣:封裝成能夠以對象的形式存在,同時可以使用getter & setter方法的實行。

(2)封裝哪些方法

get()、set(name, value, opts)、remove(name)、clear()、getCookies()等等,個人覺得封裝這麼多方法足矣使用cookie了。

三、行動

(1)瞭解cookie, cookie的實質是HTTP cookie,在用戶端表現的對象時document.cookie.更多瞭解,可以看我下面的代碼即注釋

(2)上代碼:這些代碼應該都很直觀,並且可以配合項目代碼一起壓縮。我覺得下面的開頭的注釋是重點。

複製代碼 代碼如下:
/*
 * HTTP Cookie:儲存會話資訊
 * 名稱和值傳送時必須是經過RUL編碼的
 * cookie綁定在指定的網域名稱下,非本域無法共用cookie,但是可以是在主站共用cookie給子站
 * cookie有一些限制:比如IE6 & IE6- 限定在20個;IE7 50個;Opear 30個...所以一般會根據【必須】需求才設定cookie
 * cookie的名稱不分大小寫;同時建議將cookie URL編碼;路徑是區分cookie在不同情況下傳遞的好方式;帶安全標誌cookie
 *     在SSL情況下發送到伺服器端,http則不會。建議針對cookie設定expires、domain、 path;每個cookie小於4KB
 * */
//對cookie的封裝,採取getter、setter方式
(function(global){
    //擷取cookie對象,以對象表示
    function getCookiesObj(){
        var cookies = {};
        if(document.cookie){
            var objs = document.cookie.split('; ');
            for(var i in objs){
                var index = objs[i].indexOf('='),
                    name = objs[i].substr(0, index),
                    value = objs[i].substr(index + 1, objs[i].length);   
                cookies[name] = value;
            }
        }
        return cookies;
    }
    //設定cookie
    function set(name, value, opts){
        //opts maxAge, path, domain, secure
        if(name && value){
            var cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value);
            //選擇性參數
            if(opts){
                if(opts.maxAge){
                    cookie += '; max-age=' + opts.maxAge;
                }
                if(opts.path){
                    cookie += '; path=' + opts.path;
                }
                if(opts.domain){
                    cookie += '; domain=' + opts.domain;
                }
                if(opts.secure){
                    cookie += '; secure';
                }
            }
            document.cookie = cookie;
            return cookie;
        }else{
            return '';
        }
    }
    //擷取cookie
    function get(name){
        return decodeURIComponent(getCookiesObj()[name]) || null;
    }
    //清除某個cookie
    function remove(name){
        if(getCookiesObj()[name]){
            document.cookie = name + '=; max-age=0';
        }
    }
    //清除所有cookie
    function clear(){
        var cookies = getCookiesObj();
        for(var key in cookies){
            document.cookie = key + '=; max-age=0';
        }
    }
    //擷取所有cookies
    function getCookies(name){
        return getCookiesObj();
    }
    //解決衝突
    function noConflict(name){
        if(name && typeof name === 'string'){
            if(name && window['cookie']){
                window[name] = window['cookie'];
                delete window['cookie'];
                return window[name];
            }
        }else{
            return window['cookie'];
            delete window['cookie'];
        }
    }
    global['cookie'] = {
        'getCookies': getCookies,
        'set': set,
        'get': get,
        'remove': remove,
        'clear': clear,
        'noConflict': noConflict
    };
})(window);

 (3)example

複製代碼 代碼如下:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>cookie example</title>
    </head>
    <body>
        <script type="text/javascript" src="cookie.js" ></script>
        <script type="text/javascript">
            console.log('----------cookie對象-------------');
            console.log(cookie);
            console.log('----------對象-------------');
            console.log(cookie.getCookies());
            console.log('----------設定cookie-------------');
            console.log(cookie.set('name', 'wlh'));
            console.log('----------設定cookie 123-------------');
            console.log(cookie.set('name', 'wlh123'));
            console.log('----------設定cookie age-------------');
            console.log(cookie.set('age', 20));
            console.log('----------擷取cookie-------------');
            console.log(cookie.get('name'));
            console.log('----------擷取所有-------------');
            console.log(cookie.getCookies());
            console.log('----------清除age-------------');
            console.log(cookie.remove('age'));
            console.log('----------擷取所有-------------');
            console.log(cookie.getCookies());
            console.log('----------清除所有-------------');
            console.log(cookie.clear());
            console.log('----------擷取所有-------------');
            console.log(cookie.getCookies());
            console.log('----------解決衝突-------------');
            var $Cookie = cookie.noConflict(true /*a new name of cookie*/);
            console.log($Cookie);
            console.log('----------使用新的命名-------------');
            console.log($Cookie.getCookies());
        </script>
    </body>
</html>

(4)代碼地址:https://github.com/vczero/cookie

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.