美文网首页
JavaScript操作cookie的封装方法

JavaScript操作cookie的封装方法

作者: 怪兽君MT | 来源:发表于2018-08-22 22:29 被阅读0次

    前言:

    摘自《JavaScript高级程序设计》(第3版)第631页。

    记录于此,以便日后查阅


    封装方法

    var CookieUtil = {
    
        get: function (name) {
            var cookieName = encodeURIComponent(name) + '=',
                cookieStart = document.cookie.indexOf(cookieName),
                cookieValue = null;
            
            if (cookieStart > -1) {
                var cookieEnd = document.cookie.indexOf(';', cookieStart);
                if (cookieEnd == -1) {
                    cookieEnd = document.cookie.length;
                }
                cookieValue = decodeURIComponent(document.cookie.subString(cookieStart + cookieName.length, cookieEnd));
            }
    
            return cookieValue;
        },
    
        set: function (name, value, expires, path, domain, secure) {    // name和value是必须,其他参数可以不设
            var cookieText = encodeURIComponent(name) + '=' + encodeURIComponent(value);
    
            if (expires instanceof Date) {
                cookieText += '; expires=' + expires.toGMTString();
            }
    
            if (path) {
                cookieText += '; path=' + path;
            }
    
            if (domain) {
                cookieText += '; domain=' + domain;
            }
    
            if (secure) {
                cookieText += '; secure';
            }
    
            document.cookie = cookieText;
        },
    
        unset: function (name, path, domain, secure) {    // 删除,name必须
            this.set(name, '', new Date(0), path, domain, secure);
        }
    
    };
    

    相关文章

      网友评论

          本文标题:JavaScript操作cookie的封装方法

          本文链接:https://www.haomeiwen.com/subject/rbjuiftx.html