API lưu trữ web
API lưu trữ web là một cú pháp đơn giản để lưu trữ và truy xuất dữ liệu trong trình duyệt. Nó rất dễ sử dụng:
API lưu trữ web được hỗ trợ trong tất cả các trình duyệt:
Chrome | IE/Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes |
Đối tượng lưu trữ cục bộ
Đối tượng localStorage cung cấp quyền truy cập vào bộ nhớ cục bộ cho một Trang Web cụ thể. Nó cho phép bạn lưu trữ, đọc, thêm, sửa đổi và xóa các mục dữ liệu cho miền đó.
Dữ liệu được lưu trữ không có ngày hết hạn và sẽ không bị xóa khi đóng trình duyệt.
Dữ liệu sẽ có sẵn trong nhiều ngày, tuần và năm.
Phương thức setItem()
Phương thức localStorage.setItem() lưu trữ một mục dữ liệu trong bộ lưu trữ.
Nó lấy tên và giá trị làm tham số:
Ví dụ
localStorage.setItem("name", "John Doe");
Phương thức getItem()
Phương thức localStorage.getItem() lấy một mục dữ liệu từ bộ lưu trữ.
Nó lấy tên làm tham số:
Ví dụ
localStorage.getItem("name");
Đối tượng sessionStorage
Đối tượng sessionStorage giống hệt với đối tượng localStorage.
Sự khác biệt là đối tượng sessionStorage lưu trữ dữ liệu trong một phiên.
Dữ liệu sẽ bị xóa khi đóng trình duyệt.
Phương thức setItem()
Phương thức sessionStorage.setItem() lưu trữ một mục dữ liệu trong bộ lưu trữ.
Nó lấy tên và giá trị làm tham số:
Ví dụ
sessionStorage.setItem("name", "John Doe");
Phương thức getItem()
Phương thức sessionStorage.getItem() lấy một mục dữ liệu từ bộ lưu trữ.
Nó lấy tên làm tham số:
Ví dụ
sessionStorage.getItem("name");
Thuộc tính và phương thức đối tượng lưu trữ
Property/Method | Description |
---|---|
key( n ) | Returns the name of the n th key in the storage |
length | Returns the number of data items stored in the Storage object |
getItem( keyname ) | Returns the value of the specified key name |
setItem( keyname , value ) | Adds a key to the storage, or updates a key value (if it already exists) |
removeItem( keyname ) | Removes that key from the storage |
clear() | Empty all key out of the storage |
Các trang liên quan đến API lưu trữ web
Property | Description |
---|---|
window.localStorage | Allows to save key/value pairs in a web browser. Stores the data with no expiration date |
window.sessionStorage | Allows to save key/value pairs in a web browser. Stores the data for one session |