Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Đọc Cookie bằng JavaScript

Khái niệm

document.cookie cho phép đọc/ghi cookie của domain hiện tại. Trả về string chứa tất cả cookie cách nhau bởi ; .

Ví dụ: Đọc/Ghi Cookie

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Read Cookie</title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; padding: 20px; }
        .result { font-size: 16px; font-weight: 500; color: #6a1b9a; margin: 20px 0; padding: 15px; background: #f3e5f5; border-radius: 4px; white-space: pre-wrap; }
        button { padding: 10px 20px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; margin: 5px; }
        input { padding: 8px; margin: 5px; border: 1px solid #ddd; border-radius: 4px; }
    </style>
</head>
<body>
    <h1>Đọc/Ghi Cookie bằng JavaScript</h1>
    <div class="result" id="result"></div>
    <button id="btnRead">ĐỌC COOKIE</button>
    <button id="btnSet">SET COOKIE TEST</button>
    <button id="btnDelete">XÓA COOKIE</button>
    <h3>⚠️ Cần chạy trên localhost (https://localhost) - không chạy file://</h3>

    <script>
        const resEle = document.getElementById('result');
        const btnRead = document.getElementById('btnRead');
        const btnSet = document.getElementById('btnSet');
        const btnDelete = document.getElementById('btnDelete');

        // Set cookie
        btnSet.addEventListener('click', () => {
            const name = 'username';
            const value = 'Nguyen Van A';
            const days = 7;
            const expires = new Date(Date.now() + days * 864e5).toUTCString();
            document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expires}; path=/; SameSite=Lax`;
            resEle.textContent = `Đã set cookie: ${name}=${value} (hết hạn ${days} ngày)`;
        });

        // Read cookie
        btnRead.addEventListener('click', () => {
            const allCookies = document.cookie;
            if (!allCookies) {
                resEle.textContent = 'Không có cookie nào';
                return;
            }
            
            resEle.textContent = 'Tất cả cookie:\n' + allCookies.split('; ').join('\n');
            
            // Parse thành object
            const cookies = {};
            allCookies.split('; ').forEach(c => {
                const [key, ...val] = c.split('=');
                cookies[key] = decodeURIComponent(val.join('='));
            });
            resEle.textContent += '\n\nParsed object:\n' + JSON.stringify(cookies, null, 2);
        });

        // Delete cookie
        btnDelete.addEventListener('click', () => {
            document.cookie = 'username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
            resEle.textContent = 'Đã xóa cookie username';
        });

        // Auto read on load
        btnRead.click();
    </script>
</body>
</html>

Kết quả

Click "SET COOKIE TEST" → "ĐỌC COOKIE" hiển thị:

Tất cả cookie:
username=Nguyen%20Van%20A

Parsed object:
{
  "username": "Nguyen Van A"
}

Helper Functions (Khuyên dùng)

// Set cookie với options đầy đủ
function setCookie(name, value, options = {}) {
    const defaults = {
        path: '/',
        sameSite: 'Lax',
        secure: location.protocol === 'https:'
    };
    const opts = { ...defaults, ...options };
    
    let cookieStr = `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
    
    if (opts.expires instanceof Date) {
        cookieStr += `; expires=${opts.expires.toUTCString()}`;
    } else if (opts.maxAge) {
        cookieStr += `; max-age=${opts.maxAge}`;
    }
    
    if (opts.domain) cookieStr += `; domain=${opts.domain}`;
    if (opts.path) cookieStr += `; path=${opts.path}`;
    if (opts.secure) cookieStr += '; secure';
    if (opts.sameSite) cookieStr += `; samesite=${opts.sameSite}`;
    
    document.cookie = cookieStr;
}

// Get cookie by name
function getCookie(name) {
    const match = document.cookie.match(new RegExp('(^|; )' + name + '=([^;]+)'));
    return match ? decodeURIComponent(match[2]) : null;
}

// Delete cookie
function deleteCookie(name, options = {}) {
    setCookie(name, '', { ...options, maxAge: -1 });
}

// Usage
setCookie('token', 'abc123', { maxAge: 3600, secure: true }); // 1 hour
console.log(getCookie('token')); // 'abc123'
deleteCookie('token');

Lưu ý quan trọng

  • ⚠️ Chạy trên localhost/server - file:// không hoạt động
  • Cookie size limit: ~4KB per cookie
  • HttpOnly cookie: Không đọc được bằng JS (bảo mật)
  • SameSite: Lax (mặc định), Strict, None (cần Secure)
  • Dùng encodeURIComponent/decodeURIComponent cho giá trị

Alternatives hiện đại

  • localStorage/sessionStorage: 5-10MB, chỉ client-side, không gửi server tự động
  • IndexedDB: Large structured data
  • Cache API: Offline support