Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

อ่าน Cookie ด้วย JavaScript

Cookie เป็นข้อมูลเล็กๆ ที่เก็บไว้ในเบราว์เซอร์ JavaScript เข้าถึงได้ผ่าน document.cookie แต่รูปแบบเป็น String เดียว ต้อง Parse เอง

รูปแบบของ document.cookie

"name1=value1; name2=value2; name3=value3"

ตัวอย่าง: ตั้งค่าและอ่าน Cookie

<!DOCTYPE html>
<html lang="th">
<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", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
        .result { font-size: 18px; font-weight: 500; color: blueviolet; }
        button { padding: 8px 16px; margin: 10px 0; cursor: pointer; }
        .note { background: #fff3cd; padding: 10px; border-radius: 4px; margin: 10px 0; }
    </style>
</head>
<body>
    <h1>อ่าน Cookie ด้วย JavaScript</h1>
    <div class="note">⚠️ ต้องรันผ่าน HTTP Server (localhost) ไม่ทำงานกับ file:// protocol
    <div class="result" id="cookieDisplay"></div>
    <button class="Btn" id="readBtn">อ่าน Cookie</button>
    <button class="Btn" id="setBtn" style="background: #28a745;">ตั้งค่า Cookie ทดสอบ</button>
    <h3>กด "ตั้งค่า Cookie" แล้วกด "อ่าน Cookie"</h3>

    <script>
        const readBtn = document.getElementById("readBtn");
        const setBtn = document.getElementById("setBtn");
        const display = document.getElementById("cookieDisplay");
        
        setBtn.addEventListener("click", () => {
            // ตั้งค่า Cookie พร้อม Options
            document.cookie = "username=Somchai; max-age=86400; path=/; SameSite=Lax";
            document.cookie = "theme=dark; max-age=86400; path=/";
            document.cookie = "sessionId=abc123; max-age=3600; path=/; Secure; HttpOnly"; // HttpOnly ไม่อ่านได้จาก JS
            display.innerHTML = "✅ ตั้งค่า Cookie 3 รายการแล้ว (1 รายการ HttpOnly จะอ่านไม่ได้)";
        });
        
        readBtn.addEventListener("click", () => {
            const allCookies = document.cookie;
            display.innerHTML = `Raw Cookie String:
${allCookies || "(ว่าง)"}

`; if (allCookies) { display.innerHTML += "Parsed:
"; allCookies.split("; ").forEach(cookie => { const [name, ...valueParts] = cookie.split("="); const value = valueParts.join("="); // ป้องกันค่าที่มี = อยู่ในนั้น display.innerHTML += `${name} = ${value}
`; }); } }); // Helper: อ่าน Cookie เฉพาะชื่อ function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(";").shift(); return null; } // Demo getCookie setTimeout(() => { console.log("getCookie('username'):", getCookie("username")); }, 100); </script> </body> </html>

ผลลัพธ์

กด "ตั้งค่า Cookie" → กด "อ่าน Cookie" → แสดง:
username=Somchai; theme=dark; sessionId=abc123
(cookie ที่ HttpOnly จะไม่แสดง)

Cookie Options (Attributes)

Attributeคำอธิบายตัวอย่าง
max-ageอายุเป็นวินาที (แทน expires)max-age=86400 (1 วัน)
expiresวันหมดอายุ (GMT String)expires=Fri, 31 Dec 2025 23:59:59 GMT
pathPath ที่ Cookie ทำงานpath=/ (ทั้งไซต์)
domainDomain ที่ Cookie ทำงานdomain=.example.com (Subdomains ทั้งหมด)
Secureส่งเฉพาะ HTTPS เท่านั้นSecure (ไม่มีค่า)
HttpOnlyJavaScript อ่านไม่ได้ (Security)HttpOnly (ไม่มีค่า)
SameSiteควบคุม Cross-site RequestSameSite=Lax / Strict / None

Helper Functions ที่นิยมใช้

// ตั้งค่า Cookie
function setCookie(name, value, days = 7, options = {}) {
    const expires = new Date(Date.now() + days * 864e5).toUTCString();
    const parts = [`${encodeURIComponent(name)}=${encodeURIComponent(value)}`, `expires=${expires}`, "path=/"];
    if (options.secure) parts.push("Secure");
    if (options.httpOnly) parts.push("HttpOnly"); // ต้องตั้งจาก Server เท่านั้น
    if (options.sameSite) parts.push(`SameSite=${options.sameSite}`);
    if (options.domain) parts.push(`domain=${options.domain}`);
    document.cookie = parts.join("; ");
}

// อ่าน Cookie
function getCookie(name) {
    return document.cookie.split("; ").reduce((acc, cookie) => {
        const [key, ...val] = cookie.split("=");
        return key === name ? decodeURIComponent(val.join("=")) : acc;
    }, null);
}

// ลบ Cookie
function deleteCookie(name, options = {}) {
    setCookie(name, "", -1, options); // max-age ติดลบ = ลบ
}

Security Best Practices

  • ✅ ใช้ HttpOnly สำหรับ Session/Auth Cookies (ป้องกัน XSS)
  • ✅ ใช้ Secure ใน Production (HTTPS Only)
  • ✅ ใช้ SameSite=Lax หรือ Strict (ป้องกัน CSRF)
  • ❌ ไม่ควรเก็บข้อมูล nhạy cảmใน Cookie ที่ JavaScript อ่านได้
  • ❌ ไม่ควรเก็บข้อมูลขนาดใหญ่ (Cookie ส่งทุก Request → ช้า)