Home > Web Front-end > JS Tutorial > Cookie encapsulation and usage guide made by javascript_javascript skills

Cookie encapsulation and usage guide made by javascript_javascript skills

WBOY
Release: 2016-05-16 16:22:40
Original
1131 people have browsed it

1. Foreword

Previously, when 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.

2. 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. 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 can be implemented using getter & setter methods.

(2) Which methods are encapsulated

get(), set(name, value, opts), remove(name), clear(), getCookies(), etc. I personally think that encapsulating so many methods is enough to use cookies.

3. 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) Above 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.

Copy code The code is as follows:

/*
* HTTP Cookie: stores session information
* Names and values ​​must be RUL encoded when transmitted
* Cookies are bound to the specified domain name. Cookies cannot be shared with non-local domains, but cookies can be shared from the main site to sub-sites
* Cookies have some restrictions: for example, IE6 & IE6- are limited to 20; IE7 50; Opear 30... so cookies are generally set according to [must] needs
* The name of the cookie is not case-sensitive; it is also recommended to encode the cookie URL; the path is a good way to distinguish the cookie delivery under different circumstances; with a security mark cookie
* In the case of SSL, it is sent to the server, but not in http. It is recommended to set expires, domain, and path for cookies; each cookie is less than 4KB
* */
//Encapsulate cookies using getter and setter methods
(function(global){
//Get the cookie object, expressed as an object
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;
}
//Set cookie
Function set(name, value, opts){
​​​​ //opts maxAge, path, domain, secure
If(name && value){
               var cookie = encodeURIComponent(name) '=' encodeURIComponent(value);
​​​​​​ //Optional parameters
                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 '';
}
}
//Get cookie
Function get(name){
          return decodeURIComponent(getCookiesObj()[name]) || null;
}
//Clear a 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

复制代码 代码如下:



   
       
        cookie example
   
   
       
       
   

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

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