บทนำ
HTML5 Web Storage ให้เก็บข้อมูลฝั่ง Client (Key-Value) แทน Cookies ข้อดี: ขนาดใหญ่กว่า (5-10MB), ไม่ส่งไป Server ทุก Request, API ง่าย
เปรียบเทียบ
| คุณสมบัติ | sessionStorage | localStorage |
|---|---|---|
| อายุข้อมูล | จนกว่าจะปิด Tab/Window | ถาวร (จนกว่าจะลบ) |
| ขอบเขต | ต่อ Tab (แต่ละ Tab แยกกัน) | ต่อ Origin (Domain+Protocol+Port) |
| ส่งไป Server | ไม่ | ไม่ |
| ขนาด | ~5-10 MB | ~5-10 MB |
| เหมาะสำหรับ | Session Data, Form Draft, Temp State | Preferences, 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);
});