JavaScript และ `Web Storage`
บทความนี้อธิบายเกี่ยวกับ JavaScript และ Web Storage
Web Storage
เป็นกลไกที่ทรงพลังและเรียบง่ายในการจัดเก็บข้อมูลในเบราว์เซอร์ โดยหลักๆจะแบ่งเป็น 2 ชนิดคือ localStorage
และ sessionStorage
เราจะอธิบายความแตกต่าง วิธีการใช้ และโค้ดตัวอย่างทีละขั้นตอน
YouTube Video
javascript-web-storage-iframe.html
1<!DOCTYPE html>
2<html>
3
4<head>
5 <title>Web Storage Demo</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,
45 .right-column {
46 flex: 1 1 200px;
47 min-width: 200px;
48 }
49
50 h1,
51 h2 {
52 font-size: 1.2rem;
53 color: #007bff;
54 margin-top: 0.5em;
55 margin-bottom: 0.5em;
56 border-left: 5px solid #007bff;
57 padding-left: 0.6em;
58 background-color: #e9f2ff;
59 }
60
61 button {
62 display: block;
63 margin: 1em auto;
64 padding: 0.75em 1.5em;
65 font-size: 1rem;
66 background-color: #007bff;
67 color: white;
68 border: none;
69 border-radius: 6px;
70 cursor: pointer;
71 transition: background-color 0.3s ease;
72 }
73
74 button:hover {
75 background-color: #0056b3;
76 }
77
78 #output {
79 margin-top: 1em;
80 background-color: #1e1e1e;
81 color: #0f0;
82 padding: 1em;
83 border-radius: 8px;
84 min-height: 200px;
85 font-family: Consolas, monospace;
86 font-size: 0.95rem;
87 overflow-y: auto;
88 white-space: pre-wrap;
89 }
90
91 .highlight {
92 outline: 3px solid #ffc107;
93 /* yellow border */
94 background-color: #fff8e1;
95 /* soft yellow background */
96 transition: background-color 0.3s ease, outline 0.3s ease;
97 }
98
99 .active {
100 background-color: #28a745;
101 /* green background */
102 color: #fff;
103 box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
104 transition: background-color 0.3s ease, box-shadow 0.3s ease;
105 }
106
107 body.dark {
108 background-color: black;
109 color: white;
110 }
111 </style>
112</head>
113
114<body>
115 <button onclick="testLocalStorage()">Test Local Storage</button>
116
117 <script>
118 function testLocalStorage() {
119 // Test operations
120 localStorage.setItem("username", "Alice"); // Save new value
121 localStorage.setItem("username", "Bob"); // Update value
122 localStorage.removeItem("username"); // Remove key
123 localStorage.setItem("theme", "dark"); // Add another key
124 localStorage.clear(); // Clear all data
125 }
126 </script>
127</body>
128
129</html>
javascript-web-storage.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
102 body.dark {
103 background-color: black;
104 color: white;
105 }
106 </style>
107</head>
108<body>
109 <div class="container">
110 <h1>JavaScript Console</h1>
111 <button id="executeBtn">Execute</button>
112 <div id="output"></div>
113 </div>
114
115 <div class="container">
116 <h1>IFrame Sample</h1>
117 <iframe src="javascript-web-storage-iframe.html" style="width: 100%;"></iframe>
118 </div>
119
120 <script>
121 // Override console.log to display messages in the #output element
122 (function () {
123 // Override console.log
124 const originalLog = console.log;
125 console.log = function (...args) {
126 originalLog.apply(console, args);
127 const message = document.createElement('div');
128 message.textContent = args.map(String).join(' ');
129 output.appendChild(message);
130 };
131
132 // Override console.error
133 const originalError = console.error;
134 console.error = function (...args) {
135 originalError.apply(console, args);
136 const message = document.createElement('div');
137 message.textContent = args.map(String).join(' ');
138 message.style.color = 'red'; // Color error messages red
139 output.appendChild(message);
140 };
141 })();
142
143 document.getElementById('executeBtn').addEventListener('click', () => {
144 // Prevent multiple loads
145 if (document.getElementById('externalScript')) return;
146
147 const script = document.createElement('script');
148 script.src = 'javascript-web-storage.js';
149 script.id = 'externalScript';
150 //script.onload = () => console.log('javascript-web-storage.js loaded and executed.');
151 //script.onerror = () => console.log('Failed to load javascript-web-storage.js.');
152 document.body.appendChild(script);
153 });
154 </script>
155</body>
156</html>
JavaScript และ Web Storage
Web Storage
คืออะไร?
Web Storage
เป็น API สำหรับจัดเก็บข้อมูลฝั่งลูกข่าย (เบราว์เซอร์ของผู้ใช้) ต่างจาก Cookies
, Web Storage
จะไม่ถูกส่งไปพร้อมกับ HTTP request และมีความจุในการจัดเก็บข้อมูลมากกว่า จึงทำให้การจัดการข้อมูลมีประสิทธิภาพมากขึ้น
Web Storage
มีพื้นที่จัดเก็บข้อมูล 2 ประเภท ซึ่งสามารถเลือกใช้งานได้ตามความต้องการ
-
localStorage
localStorage
เป็นพื้นที่จัดเก็บข้อมูลแบบถาวร ข้อมูลจะยังคงอยู่ แม้ปิดเบราว์เซอร์หรือรีสตาร์ทคอมพิวเตอร์ เหมาะสำหรับเก็บข้อมูลระยะยาว เช่น การตั้งค่าของผู้ใช้ หรือสถานะการเข้าสู่ระบบ -
sessionStorage
sessionStorage
เป็นพื้นที่จัดเก็บข้อมูลชั่วคราว มีผลเฉพาะในแท็บเดียวกัน และข้อมูลจะยังอยู่หลังจากรีเฟรชหน้าเว็บ แต่จะถูกลบโดยอัตโนมัติเมื่อปิดแท็บหรือหน้าต่าง เหมาะสำหรับเก็บสถานะชั่วคราวระหว่างหน้าเพจ
ทั้งสองแบบจัดเก็บข้อมูลในรูปแบบคีย์-ค่า (เป็นสตริง)
การใช้งานพื้นฐาน
การจัดเก็บข้อมูล
ข้อมูลสามารถจัดเก็บได้ดังนี้:
1// Save data to localStorage
2localStorage.setItem("username", "JohnDoe");
3
4// Save data to sessionStorage
5sessionStorage.setItem("theme", "dark");
- ใช้เมธอด
setItem
เพื่อจัดเก็บคู่คีย์-ค่าในlocalStorage
หรือsessionStorage
การดึงข้อมูล
ข้อมูลสามารถดึงมาใช้ได้ดังนี้:
1const username = localStorage.getItem("username");
2console.log(username); // "JohnDoe"
3
4const theme = sessionStorage.getItem("theme");
5console.log(theme); // "dark"
- ใช้
getItem()
เพื่ออ่านค่าที่จัดเก็บไว้
การลบข้อมูล
ข้อมูลสามารถถูกลบได้ดังนี้:
1// Remove a specific key
2localStorage.removeItem("username");
3
4// Clear all data
5sessionStorage.clear();
- ใช้
removeItem()
หรือclear()
เพื่อลบข้อมูลที่จัดเก็บไว้removeItem()
จะลบข้อมูลที่ตรงกับคีย์ที่ระบุเท่านั้นclear()
จะลบข้อมูลที่จัดเก็บไว้ทั้งหมด
การบันทึกและเรียกคืนอ็อบเจ็กต์
Web Storage
สามารถจัดเก็บได้เฉพาะ สตริง เท่านั้น ดังนั้น เมื่อบันทึกอ็อบเจ็กต์ คุณจะต้องแปลงเป็นสตริงโดยใช้ JSON.stringify()
และคืนค่าโดยใช้ JSON.parse()
เมื่อเรียกใช้งาน
1const user = {
2 name: "JohnDoe",
3 age: 30
4};
5
6// Save (serialize)
7localStorage.setItem("user", JSON.stringify(user));
8
9// Retrieve (deserialize)
10const savedUser = JSON.parse(localStorage.getItem("user"));
11console.log(savedUser.name); // "JohnDoe"
- แปลงอ็อบเจกต์เป็นสตริงด้วย
JSON.stringify()
ก่อนบันทึก และกู้คืนด้วยJSON.parse()
สาธิตความแตกต่างระหว่าง localStorage และ sessionStorage
1<!DOCTYPE html>
2<html>
3 <head>
4 <title>Web Storage Demo</title>
5 </head>
6 <body>
7 <input id="input" placeholder="Type your name..." />
8 <button onclick="saveToLocal()">Save to localStorage</button>
9 <button onclick="saveToSession()">Save to sessionStorage</button>
10 <button onclick="showValues()">Show Stored Values</button>
11
12 <script>
13 function saveToLocal() {
14 const value = document.getElementById("input").value;
15 localStorage.setItem("name", value);
16 alert("Saved to localStorage");
17 }
18
19 function saveToSession() {
20 const value = document.getElementById("input").value;
21 sessionStorage.setItem("name", value);
22 alert("Saved to sessionStorage");
23 }
24
25 function showValues() {
26 const local = localStorage.getItem("name");
27 const session = sessionStorage.getItem("name");
28
29 alert(`localStorage: ${local}\nsessionStorage: ${session}`);
30 }
31 </script>
32 </body>
33</html>
1function saveToLocal() {
2 const value = document.getElementById("input").value;
3 localStorage.setItem("name", value);
4 alert("Saved to localStorage");
5}
6
7function saveToSession() {
8 const value = document.getElementById("input").value;
9 sessionStorage.setItem("name", value);
10 alert("Saved to sessionStorage");
11}
12
13function showValues() {
14 const local = localStorage.getItem("name");
15 const session = sessionStorage.getItem("name");
16
17 alert(`localStorage: ${local}\nsessionStorage: ${session}`);
18}
- โค้ดนี้เป็นตัวอย่างง่ายๆในการเก็บชื่อที่ป้อนเข้าไปในทั้ง
localStorage
หรือsessionStorage
และสามารถตรวจสอบค่าที่จัดเก็บไว้ได้
การตรวจสอบเหตุการณ์จัดเก็บข้อมูล
เมื่อเข้าถึง localStorage
เดียวกันจากหลายแท็บ คุณสามารถตรวจสอบเหตุการณ์ storage
ในอีกแท็บหนึ่งได้ เมื่อข้อมูลมีการเปลี่ยนแปลงในแท็บอื่น
1window.addEventListener("storage", function(event) {
2 console.log("Storage changed!");
3 console.log(`Key: ${event.key}`);
4 console.log(`Old Value: ${event.oldValue}`);
5 console.log(`New Value: ${event.newValue}`);
6});
- เหตุการณ์นี้ใช้ได้กับ
localStorage
เท่านั้น และจะไม่เกิดขึ้นกับsessionStorage
1// Test operations
2localStorage.setItem("username", "Alice"); // Save new value
3localStorage.setItem("username", "Bob"); // Update value
4localStorage.removeItem("username"); // Remove key
5localStorage.setItem("theme", "dark"); // Add another key
6localStorage.clear(); // Clear all data
- เหตุการณ์
storage
จะไม่ทำงานในแท็บเดียวกัน ดังนั้นคุณจะเห็นเหตุการณ์นี้เมื่อlocalStorage
ถูกแก้ไขจากแท็บหรือหน้าต่างอื่น
ตัวอย่างการใช้งานจริง: การบันทึกสถานะ Dark Mode
1<!DOCTYPE html>
2<html>
3<head>
4 <style>
5 body.dark {
6 background-color: black;
7 color: white;
8 }
9 </style>
10</head>
11<body>
12 <button onclick="toggleDarkMode()">Toggle Dark Mode</button>
13
14 <script>
15 // Load the initial state
16 if (localStorage.getItem("darkMode") === "true") {
17 document.body.classList.add("dark");
18 }
19
20 function toggleDarkMode() {
21 const isDark = document.body.classList.toggle("dark");
22 localStorage.setItem("darkMode", isDark);
23 }
24 </script>
25</body>
26</html>
1// Load the initial state
2if (localStorage.getItem("darkMode") === "true") {
3 document.body.classList.add("dark");
4}
5
6function toggleDarkMode() {
7 const isDark = document.body.classList.toggle("dark");
8 localStorage.setItem("darkMode", isDark);
9}
10
11toggleDarkMode();
- ในตัวอย่างนี้ ทุกครั้งที่กดปุ่มจะเปลี่ยนสถานะ dark mode เปิด/ปิด โดยบันทึกสถานะลงใน
localStorage
และเรียกคืนสถานะเมื่อเข้าชมครั้งถัดไป
ขีดจำกัดและข้อควรระวังในการจัดเก็บ
เมื่อใช้ Web Storage
ควรพิจารณาประเด็นต่อไปนี้:
-
ขีดจำกัดในการจัดเก็บ ขนาดพื้นที่จัดเก็บแตกต่างกันตามเบราว์เซอร์และสภาพแวดล้อม แต่โดยทั่วไปจะอยู่ที่ประมาณ 5MB
-
ความปลอดภัย เนื่องจาก JavaScript สามารถเข้าถึงข้อมูลได้โดยตรง จึง ไม่เหมาะสำหรับจัดเก็บข้อมูลสำคัญหรือข้อมูลลับ
-
การแปลงข้อมูลเป็นสตริง ข้อมูลทั้งหมดจะถูกจัดเก็บเป็นสตริงโดยอัตโนมัติ ทำให้ข้อมูลชนิดหรือประเภทของตัวแปรไม่คงอยู่
1localStorage.setItem("isLoggedIn", true);
2console.log(localStorage.getItem("isLoggedIn")); // "true"(as string)
สรุป
Web Storage
เป็นฟีเจอร์ที่มีประโยชน์มากสำหรับ การจัดเก็บข้อมูลชั่วคราวหรือถาวรในฝั่งลูกข่าย (Client-side) ของเว็บแอปพลิเคชัน สิ่งสำคัญคือต้องเข้าใจความแตกต่างและวิธีการใช้งาน localStorage
กับ sessionStorage
และเรียนรู้วิธีใช้ JSON.stringify
กับ JSON.parse
สำหรับการบันทึกและกู้คืนข้อมูล เมื่อใช้อย่างถูกต้อง จะช่วยยกระดับประสบการณ์ของผู้ใช้อย่างมาก
คุณสามารถติดตามบทความข้างต้นโดยใช้ Visual Studio Code บนช่อง YouTube ของเรา กรุณาตรวจสอบช่อง YouTube ด้วย