Home > Web Front-end > JS Tutorial > body text

Detailed explanation of how to use javascript to encapsulate cookie instances

伊谢尔伦
Release: 2017-07-22 13:59:14
Original
1152 people have browsed it

Before using cookies, they were all operated in the form of document.cookie. Although the compatibility was good, it was troublesome. I personally like to make wheels, so I encapsulated a tool class for cookies. For a long time, I have liked writing code, but I don't really like text summaries, nor do I like writing fragmentary things. It seems that I have to change it.

Ideas

(1) How to encapsulate and what to encapsulate

How to encapsulate: Use native js to encapsulate it into a tool, so that it can be used anywhere use. Encapsulating document.cookie is the best way, and all operations are based on document.cookie.

How to encapsulate it: it can exist in the form of an object, and at the same time, it can be implemented using getter & setter methods.

(2) Which methods are encapsulated?

get(), set(name, value, opts), remove(name), clear(), getCookies(), etc. I personally feel that encapsulation is There are many ways to use cookies.

Action

(1) Understand cookies. The essence of cookies is HTTP cookies. The object displayed on the client is document.cookie. For more information, you can read my code below and comment

(2) Code: These codes should be very intuitive and can be compressed together with the project code. I think the opening comment below is the key point.

/*
 * 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);
Copy after login

(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(&#39;----------cookie对象-------------&#39;);
            console.log(cookie);
            console.log(&#39;----------对象-------------&#39;);
            console.log(cookie.getCookies());
            console.log(&#39;----------设置cookie-------------&#39;);
            console.log(cookie.set(&#39;name&#39;, &#39;wlh&#39;));
            console.log(&#39;----------设置cookie 123-------------&#39;);
            console.log(cookie.set(&#39;name&#39;, &#39;wlh123&#39;));
            console.log(&#39;----------设置cookie age-------------&#39;);
            console.log(cookie.set(&#39;age&#39;, 20));
            console.log(&#39;----------获取cookie-------------&#39;);
            console.log(cookie.get(&#39;name&#39;));
            console.log(&#39;----------获取所有-------------&#39;);
            console.log(cookie.getCookies());
            console.log(&#39;----------清除age-------------&#39;);
            console.log(cookie.remove(&#39;age&#39;));
            console.log(&#39;----------获取所有-------------&#39;);
            console.log(cookie.getCookies());
            console.log(&#39;----------清除所有-------------&#39;);
            console.log(cookie.clear());
            console.log(&#39;----------获取所有-------------&#39;);
            console.log(cookie.getCookies());
            console.log(&#39;----------解决冲突-------------&#39;);
            var $Cookie = cookie.noConflict(true /*a new name of cookie*/);
            console.log($Cookie);
            console.log(&#39;----------使用新的命名-------------&#39;);
            console.log($Cookie.getCookies());
        </script>
    </body>
</html>
Copy after login

The above is the detailed content of Detailed explanation of how to use javascript to encapsulate cookie instances. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template