JavaScript操作Cookie

2014-05-08 10:42  1240人阅读  评论 (0)

接口文档

设置cookie

// 参数: 名称, 值, [ 过期时间(相对当前时间), 路径, 域名 ]
window.cookie.set('url', 'http://www.dotcoo.com');
window.cookie.set('url', 'http://www.dotcoo.com', 7 * 24 * 3600);
window.cookie.set('url', 'http://www.dotcoo.com', 7 * 24 * 3600, '/');
window.cookie.set('url', 'http://www.dotcoo.com', 7 * 24 * 3600, '/', '.dotcoo.com');

获取cookie

// 参数: [名称]
window.cookie.get(); // 返回所有cookie
window.cookie.get('url'); // 返回指定cookie
window.cookie.get().url; // 返回指定cookie

移除cookie

// 参数: 名称, [ 路径, 域名 ]
window.cookie.remove('url');
window.cookie.remove('url', '/');
window.cookie.remove('url', '/', '.dotcoo.com');

实现代码

function Cookie() {}
Cookie.prototype.get = function(name) {
    if (document.cookie == '') {
        return name == undefined ? {} : '';
    }
    var cookies = {};
    var cs = document.cookie.split('; ');
    for (var i=0; i<cs.length; i++) {
        var s = cs[i].indexOf('=');
        cookies[cs[i].substr(0, s)] = cs[i].substr(s+1);
    }
    if (name == undefined) {
        return cookies;
    }
    return cookies[name];
}
Cookie.prototype.set = function(name, value, expire, path, domain) {
    var cookie_str = encodeURIComponent(name)+'='+encodeURIComponent(value);
    if (expire != undefined) {
        cookie_str += ';expires='+(new Date(Number(new Date())+expire*1000)).toGMTString();
    }
    if (path != undefined) {
        cookie_str += ';path='+path;
    }
    if (domain != undefined) {
        cookie_str += ';domain='+domain;
    }
    document.cookie = cookie_str;
};
Cookie.prototype.remove = function(name, path, domain) {
    var cookie_str = encodeURIComponent(name)+'=';
    cookie_str += ';expires='+(new Date(0)).toGMTString();
    if (path != undefined) {
        cookie_str += ';path='+path;
    }
    if (domain != undefined) {
        cookie_str += ';domain='+domain;
    }
    document.cookie = cookie_str;
};
window.cookie = new Cookie();