Web Storage คือพื้นที่เก็บข้อมูลแบบ key-value ใน browser ประกอบด้วย localStorage และ sessionStorage โดยข้อมูลถูกเก็บเป็น string เสมอ
%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#458588", "primaryTextColor": "#fbf1c7", "primaryBorderColor": "#fabd2f", "lineColor": "#a89984", "secondaryColor": "#b8bb26", "tertiaryColor": "#d3869b", "background": "#282828", "mainBkg": "#3c3836", "textColor": "#ebdbb2"}}}%%
flowchart LR
A["JavaScript Object
ข้อมูลในโค้ด"] --> B["JSON.stringify()
แปลงเป็น string"]
B --> C["localStorage
เก็บใน Browser"]
C --> D["JSON.parse()
แปลงกลับเป็น object"]
| Storage | อายุข้อมูล | ขอบเขต | เหมาะกับ |
|---|---|---|---|
localStorage |
อยู่จนกว่าจะลบ | origin เดียวกัน | theme, preference, cart |
sessionStorage |
หายเมื่อปิด tab | tab เดียว | wizard state, temporary form |
const preference = {
theme: "dark",
fontSize: "large"
};
// บันทึก object ต้องแปลงเป็น string ก่อน
localStorage.setItem("preference", JSON.stringify(preference));
// อ่านข้อมูลจะได้ string เสมอ
const savedText = localStorage.getItem("preference");
const savedPreference = JSON.parse(savedText);
console.log(savedPreference.theme); // dark
// ลบ key เดียว
localStorage.removeItem("preference");
// ลบทั้งหมดใน localStorage ของ origin นี้
localStorage.clear();
sessionStorage.setItem("currentStep", "2");
console.log(sessionStorage.getItem("currentStep")); // 2
เมื่อปิด tab ข้อมูลใน sessionStorage จะหายไป
<button id="themeButton">เปลี่ยนธีม</button>
<script>
const button = document.getElementById("themeButton");
const savedTheme = localStorage.getItem("theme") || "light";
// ตั้งค่า theme จากข้อมูลที่เคยบันทึก
document.documentElement.dataset.theme = savedTheme;
button.addEventListener("click", () => {
const current = document.documentElement.dataset.theme;
const next = current === "light" ? "dark" : "light";
// บันทึก theme ใหม่
document.documentElement.dataset.theme = next;
localStorage.setItem("theme", next);
});
</script>
โดยที่ remaining คือพื้นที่คงเหลือ, quota คือพื้นที่ที่ browser อนุญาต, และ used คือพื้นที่ที่ใช้ไปแล้ว
JSON.stringify() ก่อนบันทึก objectgetItem() คืนค่าเป็นชนิดใด