原生JavaScript操作cookie示例

function time() {
    return Math.floor(new Date().getTime() / 1000)
}


function setcookie(name, value, expires, path, domain, secure) {
    if (typeof window === 'undefined') {
        return true
    }
    if (typeof expires === 'string' && (/^\d+$/).test(expires)) {
        expires = parseInt(expires, 10)
    }
    if (expires instanceof Date) {
        expires = expires.toUTCString()
    } else if (typeof expires === 'number') {
        expires = (new Date(expires * 1e3)).toUTCString()
    }
    const r = [name + '=' + encodeURIComponent(value)];
    let i = '';
    const s = {expires: expires, path: path, domain: domain};
    for (i in s) {
        if (s.hasOwnProperty(i)) {
            s[i] && r.push(i + '=' + s[i])
        }
    }
    if (secure) {
        r.push('secure')
    }
    window.document.cookie = r.join(';');
    return true
}


function getcookie(name) {
    let value = null;
    let cookies = window.document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
        let cookie = cookies[i].split('=');
        if (name == cookie[0].trim()) {
            value = decodeURIComponent(cookie[1])
        }
    }
    return value
}


//========== 设置cookie ==========//
setcookie('name', '张三', time() + 3600);
setcookie('age', 18, time() + 3600);
setcookie('gender', 'male', time() + 3600);


//========== 遍历cookie ==========//
let cookies = window.document.cookie.split(';');
for (let cookie of cookies) {
    let item = cookie.split('=');
    let name = item[0].trim();               // cookie键名
    let value = decodeURIComponent(item[1]); // cookie键值
    console.log(name + ' = ' + value);
}
// name = 张三
// age = 18
// gender = male


//========== 获取cookie ==========//
console.log('name =', getcookie('name'));     // name = 张三
console.log('age =', getcookie('age'));       // age = 18
console.log('gender =', getcookie('gender')); // gender = male
console.log('job =', getcookie('job'));       // job = null


//========== 删除cookie ==========//
setTimeout(function () {
    // 将cookie的过期时间设为一个已经过去的时间点即可删除cookie
    setcookie('name', '', time() - 3600);
    setcookie('age', '', time() - 3600);
    setcookie('gender', '', time() - 3600);
}, 5000);

Copyright © 2024 码农人生. All Rights Reserved