JavaScript และคุกกี้
บทความนี้อธิบายเกี่ยวกับ JavaScript และคุกกี้
เราจะอธิบายทุกอย่างอย่างละเอียดทีละขั้น ตั้งแต่พื้นฐานของคุกกี้ การอ่านและเขียน ความปลอดภัย ไปจนถึงตัวอย่างการใช้งานจริง
YouTube Video
javascript-cookie.html
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>JavaScript & HTML</title>
6 <style>
7 * {
8 box-sizing: border-box;
9 }
10
11 body {
12 margin: 0;
13 padding: 1em;
14 padding-bottom: 10em;
15 font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
16 background-color: #f7f9fc;
17 color: #333;
18 line-height: 1.6;
19 }
20
21 .container {
22 max-width: 800px;
23 margin: 0 auto;
24 padding: 1em;
25 background-color: #ffffff;
26 border: 1px solid #ccc;
27 border-radius: 10px;
28 box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
29 }
30
31 .container-flex {
32 display: flex;
33 flex-wrap: wrap;
34 gap: 2em;
35 max-width: 1000px;
36 margin: 0 auto;
37 padding: 1em;
38 background-color: #ffffff;
39 border: 1px solid #ccc;
40 border-radius: 10px;
41 box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
42 }
43
44 .left-column, .right-column {
45 flex: 1 1 200px;
46 min-width: 200px;
47 }
48
49 h1, h2 {
50 font-size: 1.2rem;
51 color: #007bff;
52 margin-top: 0.5em;
53 margin-bottom: 0.5em;
54 border-left: 5px solid #007bff;
55 padding-left: 0.6em;
56 background-color: #e9f2ff;
57 }
58
59 button {
60 display: block;
61 margin: 1em auto;
62 padding: 0.75em 1.5em;
63 font-size: 1rem;
64 background-color: #007bff;
65 color: white;
66 border: none;
67 border-radius: 6px;
68 cursor: pointer;
69 transition: background-color 0.3s ease;
70 }
71
72 button:hover {
73 background-color: #0056b3;
74 }
75
76 #output {
77 margin-top: 1em;
78 background-color: #1e1e1e;
79 color: #0f0;
80 padding: 1em;
81 border-radius: 8px;
82 min-height: 200px;
83 font-family: Consolas, monospace;
84 font-size: 0.95rem;
85 overflow-y: auto;
86 white-space: pre-wrap;
87 }
88
89 .highlight {
90 outline: 3px solid #ffc107; /* yellow border */
91 background-color: #fff8e1; /* soft yellow background */
92 transition: background-color 0.3s ease, outline 0.3s ease;
93 }
94
95 .active {
96 background-color: #28a745; /* green background */
97 color: #fff;
98 box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
99 transition: background-color 0.3s ease, box-shadow 0.3s ease;
100 }
101 </style>
102</head>
103<body>
104 <div class="container">
105 <h1>JavaScript Console</h1>
106 <button id="executeBtn">Execute</button>
107 <div id="output"></div>
108 </div>
109
110 <script>
111 // Override console.log to display messages in the #output element
112 (function () {
113 // Override console.log
114 const originalLog = console.log;
115 console.log = function (...args) {
116 originalLog.apply(console, args);
117 const message = document.createElement('div');
118 message.textContent = args.map(String).join(' ');
119 output.appendChild(message);
120 };
121
122 // Override console.error
123 const originalError = console.error;
124 console.error = function (...args) {
125 originalError.apply(console, args);
126 const message = document.createElement('div');
127 message.textContent = args.map(String).join(' ');
128 message.style.color = 'red'; // Color error messages red
129 output.appendChild(message);
130 };
131 })();
132
133 document.getElementById('executeBtn').addEventListener('click', () => {
134 // Prevent multiple loads
135 if (document.getElementById('externalScript')) return;
136
137 const script = document.createElement('script');
138 script.src = 'javascript-cookie.js';
139 script.id = 'externalScript';
140 //script.onload = () => console.log('javascript-cookie.js loaded and executed.');
141 //script.onerror = () => console.log('Failed to load javascript-cookie.js.');
142 document.body.appendChild(script);
143 });
144 </script>
145</body>
146</html>
JavaScript และคุกกี้
คุกกี้
หมายถึง ข้อมูลขนาดเล็กที่ถูกเก็บไว้ในเบราว์เซอร์ของผู้ใช้ โดยส่วนใหญ่จะถูกใช้เพื่อวัตถุประสงค์ดังต่อไปนี้:
- การยืนยันตัวผู้ใช้ (รักษาสถานะการเข้าสู่ระบบ)
- บันทึกการตั้งค่าของผู้ใช้ (ภาษา, ธีม ฯลฯ)
- ติดตามพฤติกรรม (ประวัติการเข้าชม ฯลฯ)
ใน JavaScript คุณสามารถอ่านและเขียนคุกกี้โดยใช้ document.cookie
การสร้าง (เขียน) คุกกี้
สามารถสร้างคุกกี้ได้ด้วยรูปแบบต่อไปนี้:
1document.cookie = "username=JohnDoe";
- โค้ดนี้จะบันทึกคุกกี้ชื่อ
"username=JohnDoe"
ลงในเบราว์เซอร์
การสร้างคุกกี้ที่มีวันหมดอายุ
คุกกี้สามารถกำหนดวันหมดอายุได้ หากไม่ได้ตั้งวันหมดอายุไว้ จะถูกจัดการเป็น คุกกี้เซสชัน และถูกลบเมื่อปิดเบราว์เซอร์
1const date = new Date();
2date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days
3const cookieText = "username=JohnDoe; expires=" + date.toUTCString() + "; path=/; SameSite=None; Secure"
4document.cookie = cookieText;
5console.log(`Cookie Text : ${cookieText}`);
6console.log(`Cookie Value : ${document.cookie}`);
- แอตทริบิวต์
expires
กำหนดวันหมดอายุของคุกกี้ในรูปแบบเวลา UTC - แอตทริบิวต์
path
กำหนดเส้นทางที่คุกกี้จะถูกส่งไป/
หมายถึงทั้งเว็บไซต์ - หากคุณระบุ
SameSite=None
Cookie
จะถูกส่งแม้มีการร้องขอข้ามเว็บไซต์ อย่างไรก็ตาม ในกรณีนี้ คุณต้องใส่คุณสมบัติSecure
เสมอ - การกำหนด
Secure
จะจำกัดให้Cookie
ถูกส่งเฉพาะการสื่อสารผ่าน HTTPS ซึ่งช่วยเพิ่มความปลอดภัย - โดยการดูที่
document.cookie
คุณจะสามารถดึงข้อมูลCookie
ทั้งหมดที่มีในหน้าปัจจุบันในรูปแบบสตริงได้ - โดยใช้
console.log
คุณสามารถตรวจสอบความแตกต่างระหว่างค่าของCookie
ที่ตั้งค่าในเบราว์เซอร์กับค่าที่สามารถเรียกดูได้
การดึงข้อมูล (อ่าน) คุกกี้
คุณสามารถดึงคุกกี้ทั้งหมดมาเป็นสตริงได้โดยใช้ document.cookie
1const date = new Date();
2date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days
3document.cookie = "theme=dark; expires=" + date.toUTCString() + "; path=/; SameSite=None; Secure"
4
5console.log(document.cookie);
6// Output: "username=JohnDoe; theme=dark"
- ค่าที่ได้จาก
document.cookie
จะเป็นสตริงเดียวซึ่งนำCookie
ทั้งหมดมาต่อกันในรูปแบบ 'key=value;
' - จะสะดวกกว่าหากใช้ฟังก์ชันในการแยกสตริงนี้และดึงค่าที่ต้องการออกมา
ฟังก์ชันเพื่อดึงค่าของคุกกี้
1function getCookie(name) {
2 const cookies = document.cookie.split('; ');
3 for (const cookie of cookies) {
4 const [key, value] = cookie.split('=');
5 if (key === name) {
6 return decodeURIComponent(value);
7 }
8 }
9 return null;
10}
11
12console.log(getCookie("username")); // "JohnDoe"
- ฟังก์ชันนี้จะแยกคีย์และค่าโดยใช้
split()
และจะคืนค่าหากตรงกับคีย์ที่ระบุ - โดยใช้
decodeURIComponent
คุณจะสามารถดึงตัวอักษรที่ถูกเข้ารหัสให้ถูกต้อง - ถ้าไม่มีคีย์ที่ตรงกัน จะส่งคืนค่า
null
การลบคุกกี้
สามารถลบคุกกี้ได้โดยการตั้งวันหมดอายุให้เป็นวันที่ในอดีต
1document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; SameSite=None; Secure";
2
3console.log(document.cookie);
4// Output: "theme=dark"
- โดยกำหนดค่า
username
ให้ว่างเปล่าและตั้งวันหมดอายุให้อยู่ในอดีต คุกกี้จะถูกลบออก - เมื่อคุณลบ
Cookie
คุณต้องตั้งpath
,SameSite
และSecure
ให้ตรงกับค่าตอนที่สร้างคุกกี้นี้ด้วย - ในตัวอย่างนี้
username
ถูกลบออก ส่วนCookie
อื่นเช่นtheme=dark
จะยังคงอยู่
ตัวเลือกของคุกกี้
คุณสามารถกำหนดตัวเลือกต่าง ๆ เพื่อควบคุมพฤติกรรมของคุกกี้ได้ ตัวเลือกหลัก ๆ มีดังนี้:
กำหนดวันหมดอายุของคุกกี้ในรูปแบบ UTC หากไม่กำหนดไว้ คุกกี้จะกลายเป็นคุกกี้เซสชันและถูกลบเมื่อปิดเบราว์เซอร์
กำหนดวันหมดอายุของคุกกี้เป็นวินาที ค่านี้จะมีความสำคัญเหนือกว่า `expires`
กำหนดเส้นทางที่คุกกี้จะถูกส่งไป ตัวอย่างเช่น ถ้ากำหนด `/admin` คุกกี้จะถูกส่งเฉพาะเพจที่อยู่ภายใต้เส้นทางนั้นเท่านั้น
กำหนดโดเมนที่คุกกี้มีผลใช้งานได้ โดยปกติจะตั้งให้กับโดเมนปัจจุบัน แต่ก็สามารถกำหนดให้ครอบคลุมซับโดเมนทั้งหมด เช่น `.example.com` ได้
เมื่อระบุแอตทริบิวต์นี้ คุกกี้จะถูกส่งผ่าน HTTPS เท่านั้น เพื่อความปลอดภัย ควรตั้งแอตทริบิวต์นี้ไว้เสมอสำหรับข้อมูลที่สำคัญ
ควบคุมว่าคุกกี้จะถูกส่งในการร้องขอข้ามเว็บไซต์หรือไม่ คุณสามารถกำหนดค่าใดค่าหนึ่งจากสามค่าต่อไปนี้:
- `Strict`
คุกกี้จะถูกส่งเฉพาะคำร้องขอจากเว็บไซต์เดียวกันเท่านั้น
- `Lax`
คุกกี้จะถูกส่งในการนำทางตามปกติ แต่จะมีข้อจำกัดบางประการ
- `None`
คุกกี้สามารถถูกส่งได้แม้ในกรณีที่เป็นการร้องขอข้ามเว็บไซต์ แต่จำเป็นต้องตั้งค่าแอตทริบิวต์ `Secure` ด้วย
ตัวอย่าง: คุกกี้แบบปลอดภัย
1document.cookie = "sessionId=abc123; secure; SameSite=Strict";
- ถ้าคุณระบุ
secure
,Cookie
จะถูกส่งเฉพาะผ่านการสื่อสารแบบ HTTPS เท่านั้น - ถ้าคุณระบุ
SameSite=Strict
Cookie
จะไม่ถูกส่งเมื่อมีการร้องขอข้ามเว็บไซต์ ซึ่งช่วยป้องกัน CSRF ได้อย่างมีประสิทธิภาพ - คุณสมบัติด้านความปลอดภัยเหล่านี้เป็นสิ่งสำคัญสำหรับ
Cookie
ที่ใช้สำหรับการยืนยันตัวตนหรือจัดการเซสชั่น
การเข้ารหัสและถอดรหัส
เนื่องจากค่าคุกกี้อาจมีอักขระพิเศษ ควรใช้ encodeURIComponent
เพื่อความปลอดภัย
1const date = new Date();
2date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days
3
4const username = "JohnDoe";
5document.cookie =
6 "username=" + encodeURIComponent(username) +
7 "; max-age=604800; path=/; SameSite=None; Secure";
8
9console.log(decodeURIComponent(getCookie("username"))); // "JohnDoe"
- โดยใช้
encodeURIComponent
คุณจะสามารถเก็บข้อมูลที่มีช่องว่างหรือสัญลักษณ์ต่างๆ ในCookie
ได้อย่างปลอดภัย - เมื่อดึงข้อมูลออกมา ให้ใช้
decodeURIComponent
เพื่อแปลงกลับเป็นสตริงเดิม - ในตัวอย่างนี้ ใช้
max-age=604800
เพื่อกำหนดช่วงหมดอายุเป็น 7 วัน (604,800 วินาที) นี่เป็นวิธีการกำหนดวันหมดอายุซึ่งคล้ายกับexpires
max-age
สามารถระบุเป็นวินาที ทำให้ใช้งานได้ง่ายกว่า
ตัวอย่างการใช้งานจริง: การบันทึกและโหลดธีม
ตัวอย่างต่อไปนี้เป็นการบันทึกธีมที่ผู้ใช้เลือกไปยังคุกกี้ และนำมาใช้อัตโนมัติเมื่อเข้าชมครั้งถัดไป
1function setTheme(theme) {
2 document.cookie =
3 "theme=" + encodeURIComponent(theme) +
4 "; max-age=604800; path=/; SameSite=None; Secure"; // 1 week
5 applyTheme(theme);
6}
7
8function applyTheme(theme) {
9 document.body.style.backgroundColor = theme === "dark" ? "#333" : "#fff";
10 document.body.style.color = theme === "dark" ? "#fff" : "#000";
11}
12
13function getCookie(name) {
14 const cookies = document.cookie.split('; ');
15 for (const cookie of cookies) {
16 const [key, value] = cookie.split('=');
17 if (key === name) {
18 return decodeURIComponent(value);
19 }
20 }
21 return null;
22}
23
24const savedTheme = getCookie("theme");
25if (savedTheme) {
26 applyTheme(savedTheme);
27}
1<button onclick="setTheme('light')">Light</button>
2<button onclick="setTheme('dark')">Dark</button>
- ฟังก์ชัน
setTheme
จะบันทึกธีมที่เลือกลงในCookie
และเรียกapplyTheme
ทันทีเพื่ออัปเดตหน้าจอ - ฟังก์ชัน
applyTheme
จะเปลี่ยนสีพื้นหลังและสีตัวอักษรของbody
ตามธีมที่เลือก - ในตัวอย่างนี้ เนื่องจากตั้งค่า
max-age=604800
ทำให้การตั้งค่าธีมถูกเก็บไว้เป็นเวลา 1 สัปดาห์ - เนื่องจากการเลือกของผู้ใช้จะถูกเก็บไว้เมื่อลับมาเยี่ยมชมหน้าเดิม จึงช่วยให้ประสบการณ์การใช้งาน (UX) ดีขึ้น
ข้อจำกัดและข้อควรระวังเกี่ยวกับคุกกี้
ควรระวังประเด็นต่อไปนี้เมื่อใช้คุกกี้:
-
ข้อจำกัดขนาด ขนาดของคุกกี้แต่ละตัวจะถูกจำกัดไว้ประมาณ 4KB
-
ข้อจำกัดจำนวนคุกกี้ที่สามารถบันทึกได้ ขึ้นอยู่กับเบราว์เซอร์ คุณสามารถบันทึกได้ประมาณ 20 ถึง 50 ต่อโดเมนเท่านั้น
-
ข้อควรระวังด้านความปลอดภัย เนื้อหาของ
Cookie
จะถูกบันทึกในรูปแบบข้อความธรรมดา ดังนั้นจึงไม่เหมาะสำหรับการเก็บข้อมูลลับ เช่น รหัสผ่าน -
คุกกี้ที่ไม่สามารถเข้าถึงจาก JavaScript
Cookie
ที่มีคุณสมบัติHttpOnly
จะไม่สามารถอ่านได้จาก JavaScript ด้วยเหตุผลด้านความปลอดภัย
เซิร์ฟเวอร์และ Cookie
1Set-Cookie: sessionId=abc123; HttpOnly; Secure; SameSite=Strict
คุณสมบัติของ Cookie
บางอย่าง เช่น HttpOnly
ไม่สามารถตั้งค่าผ่าน JavaScript ได้ สิ่งเหล่านี้จะต้องตั้งค่าที่ฝั่งเซิร์ฟเวอร์
สรุป
การจัดการ Cookie
ด้วย JavaScript สามารถช่วยเสริมประสบการณ์ผู้ใช้และรักษาสถานะของผู้ใช้ได้ อย่างไรก็ตาม โปรดคำนึงถึงประเด็นต่อไปนี้เพื่อให้จัดการได้อย่างปลอดภัยและถูกต้อง
-
จัดเก็บเพียงข้อมูลที่จำเป็นเท่านั้น ในมุมมองด้านความปลอดภัยและความเป็นส่วนตัว ควรหลีกเลี่ยงการเก็บข้อมูลส่วนบุคคลหรือข้อมูลสำคัญ และบันทึกเฉพาะข้อมูลที่จำเป็นเท่านั้น
-
ตั้งค่าคุณสมบัติด้านความปลอดภัยให้เหมาะสม ตั้งค่าคุณสมบัติ เช่น
Secure
และSameSite
เพื่อป้องกันการโจมตีข้ามไซต์ เช่น XSS และ CSRF -
การเข้ารหัสและถอดรหัสข้อมูล ใช้
encodeURIComponent
และdecodeURIComponent
เพื่อเก็บและอ่านค่าของCookie
อย่างปลอดภัย รองรับอักขระพิเศษหรือภาษาญี่ปุ่นได้อย่างถูกต้อง
ด้วยการเรียนรู้วิธีใช้ Cookie
ที่ถูกต้อง คุณจะสามารถสร้างแอปพลิเคชันเว็บที่ทันสมัยและปลอดภัยมากยิ่งขึ้นได้
คุณสามารถติดตามบทความข้างต้นโดยใช้ Visual Studio Code บนช่อง YouTube ของเรา กรุณาตรวจสอบช่อง YouTube ด้วย