หัวข้อ 5: localStorage และ sessionStorage

คำจำกัดความ

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"]

เปรียบเทียบ localStorage และ sessionStorage

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

sessionStorage.setItem("currentStep", "2");
console.log(sessionStorage.getItem("currentStep")); // 2

เมื่อปิด tab ข้อมูลใน sessionStorage จะหายไป

ข้อจำกัด

การประยุกต์

ตัวอย่าง Theme Toggle

<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 - used

โดยที่ remaining คือพื้นที่คงเหลือ, quota คือพื้นที่ที่ browser อนุญาต, และ used คือพื้นที่ที่ใช้ไปแล้ว

แบบทดสอบหลังเรียน

  1. localStorage และ sessionStorage ต่างกันอย่างไร
  2. ทำไมต้องใช้ JSON.stringify() ก่อนบันทึก object
  3. getItem() คืนค่าเป็นชนิดใด
  4. ข้อมูลแบบใดไม่ควรเก็บใน localStorage
  5. localStorage ประยุกต์ใช้กับอะไรได้บ้าง

กลับสัปดาห์ที่ 5