เพื่อ ดึง (Retrieve) Element จาก Local Storage ต้องตรวจสอบก่อนว่า Browser รองรับ Local Storage หรือไม่ แล้ว Set Element ใน Local Storage ต้องระวังเพราะปิด Browser แล้วข้อมูลจะไม่ถูกเก็บ แล้วค่อยดึงข้อมูลที่เก็บไว้ มาดูรายละเอียดกัน
Syntax สำหรับ Set ข้อมูลใน Local Storage
localStorage.setItem();
ตัวอย่าง
ในตัวอย่างนี้ ตรวจสอบ ความเข้ากันได้ (Compatibility) ของ Storage ด้วย If Condition แล้วใช้ localStorage.setItem() วาง Item ใน Local Storage เมื่อ Item อยู่ใน Local Storage แล้ว ใช้ Property localStorage.getItem() ดึงข้อมูล
<html> <body> <p id = "storage"></p> <script> if (typeof(Storage) !== "undefined") { localStorage.setItem("product", "Tutorix"); document.getElementById("storage").innerHTML = localStorage.getItem("product"); } else { document.getElementById("storage").innerHTML = "Sorry, no Web Storage compatibility..."; } </script> </body> </html>
ผลลัพธ์
Tutorix