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

เก็บข้อมูลในเบราว์เซอร์ด้วย HTML5 localStorage API


localStorage บันทึกข้อมูล string ในเบราว์เซอร์ ไม่มีวันหมดอายุ แตกต่างจาก sessionStorage ที่หายเมื่อปิดเบราว์เซอร์

Local Storage ออกแบบสำหรับเก็บข้อมูลข้ามหน้าต่างและข้ามเซสชัน Web apps อาจเก็บข้อมูลผู้ใช้หลายเมกะไบต์ฝั่ง client เพื่อประสิทธิภาพ

ตัวอย่าง: นับจำนวนครั้งที่เข้าชม

<!DOCTYPE HTML> <html>    <body>       <script type = "text/javascript">          if( localStorage.hits ){             localStorage.hits = Number(localStorage.hits) +1;          }else{             localStorage.hits = 1;          }          document.write("Total Hits: " + localStorage.hits );       </script>       <p>รีเฟรชหน้านี้เพื่อเพิ่มจำนวนเข้าชม</p>       <p>ปิดหน้าต่างเปิดใหม่ ดูผลลัพธ์</p>    </body> </html>

เมธอดหลัก

  • setItem(key, value) - บันทึก
  • getItem(key) - อ่าน
  • removeItem(key) - ลบ
  • clear() - ล้างทั้งหมด

ข้อมูลคงอยู่แม้ปิดเบราว์เซอร์ เหมาะสำหรับ preferences, shopping cart, drafts, authentication tokens