返回列表

用 Javascript 操作 Cookie

默认分类 2016/11/09 07:13

cookie 操作操作:

var hui = {};
hui.getCookie = hui.getCookie || function(name) {
    var start = document.cookie.indexOf(name + '=');
    var len = start + name.length + 1;
    if ((!start) && (name != document.cookie.substring(0, name.length))) {
        return undefined;
    }
    if (start == -1) return undefined;
    var end = document.cookie.indexOf(';', len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len, end));
};
hui.setCookie = hui.setCookie || function(name, value, expires, path, domain, secure) {
    expires = expires === undefined ? 100 * 360 * 24 * 60 * 60 * 1000 : (expires || 0);
    var expires_date = new Date((new Date()).getTime() + expires);
    document.cookie = name + '=' + escape(value) + ';expires=' + expires_date.toGMTString() +
        (path ? ';path=' + path : '') + (domain ? ';domain=' + domain : '') + (secure ? ';secure' : '');
};
hui.removeCookie = hui.removeCookie || function(name, path, domain) {
    if (hui.getCookie(name)) document.cookie = name + '=' + (path ? ';path=' + path : '') + (domain ? ';domain=' + domain : '') + ';expires=' + (new Date(0)).toGMTString();
};

示例:

var cookie = hui.getCookie('cookieid');
if (!cookie) hui.setCookie('cookieid',  parseInt(Math.random() * 10E15) + '' + parseInt(Math.random() * 10E15), undefined, '/')
cookie = hui.getCookie('cookieid');
>> "73471651793928435282911762990985"
hui.removeCookie('cookieid', '/')
>> undefined
var cookie = hui.getCookie('cookieid');
if (!cookie) hui.setCookie('cookieid',  parseInt(Math.random() * 10E15) + '' + parseInt(Math.random() * 10E15))
cookie = hui.getCookie('cookieid');
>> "76622325535576098107776496738259"
hui.removeCookie('cookieid')
>> undefined