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

วิธาใช้ HTML5 localStorage และ sessionStorage


บทนำ

HTML5 Web Storage ให้เก็บข้อมูลฝั่ง Client (Key-Value) แทน Cookies ข้อดี: ขนาดใหญ่กว่า (5-10MB), ไม่ส่งไป Server ทุก Request, API ง่าย

เปรียบเทียบ

คุณสมบัติsessionStoragelocalStorage
อายุข้อมูลจนกว่าจะปิด Tab/Windowถาวร (จนกว่าจะลบ)
ขอบเขตต่อ Tab (แต่ละ Tab แยกกัน)ต่อ Origin (Domain+Protocol+Port)
ส่งไป Serverไม่ไม่
ขนาด~5-10 MB~5-10 MB
เหมาะสำหรับSession Data, Form Draft, Temp StatePreferences, Cache, User Data, Token

API หลัก (เหมือนกันทั้งคู่)

  • setItem(key, value) - บันทึก (Value ต้องเป็น String)
  • getItem(key) - อ่านค่า
  • removeItem(key) - ลบค่า
  • clear() - ลบทั้งหมด
  • key(index) - ชื่อ Key ตามลำดับ
  • length - จำนวน Items

ตัวอย่าง Session Storage (นับ Hit ต่อ Session)

<!DOCTYPE HTML>
<html>
  <body>
    <script>
      if (sessionStorage.hits) {
        sessionStorage.hits = Number(sessionStorage.hits) + 1;
      } else {
        sessionStorage.hits = 1;
      }
      document.write("Total Hits (Session): " + sessionStorage.hits);
    </script>
    <p>Refresh หน้านี้เพื่อเพิ่ม Hits. ปิด Tab แล้วเปิดใหม่ จะ Reset.</p>
  </body>
</html>

ตัวอย่าง Local Storage (นับ Hit ถาวร)

<!DOCTYPE HTML>
<html>
  <body>
    <script>
      if (localStorage.hits) {
        localStorage.hits = Number(localStorage.hits) + 1;
      } else {
        localStorage.hits = 1;
      }
      document.write("Total Hits (Local): " + localStorage.hits);
    </script>
    <p>Refresh หรือ ปิด Browser เปิดใหม่ ก็ยังนับต่อ.</p>
  </body>
</html>

การเก็บ Object/Array (ต้อง JSON)

// บันทึก
localStorage.setItem('user', JSON.stringify({name: 'John', age: 30}));
// อ่าน
const user = JSON.parse(localStorage.getItem('user'));

Event: Storage Event

เมื่อ localStorage เปลี่ยนใน Tab อื่น จะยิง Event ใน Tab ปัจจุบัน (ไม่รวม Tab ที่ทำการเปลี่ยน)

window.addEventListener('storage', function(e) {
  console.log('Key:', e.key, 'Old:', e.oldValue, 'New:', e.newValue);
});