首页 > JavaScript > JS获取cookie的工具类

JS获取cookie的工具类

来源:原创 作者:thomas 分类:JavaScript 阅读:994 日期:2014-05-23

var CookieUtil = {
    /*
     * 获取cookie
     * @param {String}
     */
    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;
    },

    /*
     * 设置cookie
     */
    set : function(name, value, expires, path, domain, secure) {
        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;
    },

    /*
     * 删除cookie
     */
    unset : function(name, path, domain, secure) {
        this.set(name, "", new Date(0), path, domain, secure);
    }
};

十日谈技术博客

 

热门文章 更多>

微信扫一扫,关注技术十日谈