JavaScript 中设置与读取 Cookie

代码与范例:

function setCookie(key, value) {
    var expires = new Date();
    document.cookie = key + '=' + value + ';';
    // 此处设置过期时间为 90 天。时间增量单位为微秒
    //expires.setTime(expires.getTime() + (90 * 24 * 60 * 60 * 1000));
    //document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}

function getCookie(key) {
    var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
    return keyValue ? keyValue[2] : null;
}

说明:如果要设置过期,则需要为expires赋值。否则默认为 session cookie,可能在浏览器结束后被自动清除。