javascript制作的cookie封装及使用指南

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

javascript制作的cookie封装及使用指南

  2020-05-13 我要评论

一、前言

之前使用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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们