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:
Thí dụ
localStorage.setItem("name", "John Doe");
localStorage.getItem("name");
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ộ lưu trữ 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 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 một bộ lưu trữ.
Nó nhận một tên và một giá trị làm tham số:
Thí dụ
localStorage.setItem("name", "John Doe");
Phương thức getItem ()
Phương thức localStorage.getItem () truy xuất một mục dữ liệu từ bộ lưu trữ.
Nó có tên là tham số:
Thí dụ
localStorage.getItem("name");
Đối tượng sessionStorage
Đối tượng sessionStorage giống hệt đối tượng localStorage.
Sự khác biệt là đối tượng sessionStorage lưu trữ dữ liệu cho một phiên.
Dữ liệu sẽ bị xóa khi đóng trình duyệt.
Thí dụ
sessionStorage.getItem("name");
Phương thức setItem ()
Phương thức sessionStorage.setItem () lưu trữ một mục dữ liệu trong một bộ lưu trữ.
Nó nhận một tên và một giá trị làm tham số:
Thí dụ
sessionStorage.setItem("name", "John Doe");
Phương thức getItem ()
Phương thức sessionStorage.getItem () truy xuất một mục dữ liệu từ bộ lưu trữ.
Nó có tên là tham số:
Thí 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 nth 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 that key to the storage, or update that key's 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 cho 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 |