Thuộc tính window.sessionStorage cung cấp lưu trữ cặp key-value trong trình duyệt cho một phiên (session). Dữ liệu tự động xóa khi đóng tab/cửa sổ.
Cú pháp
window.sessionStorage
Phương thức chính
| Phương thức | Mô tả |
|---|---|
setItem(key, value) | Lưu cặp key-value (chuỗi) |
getItem(key) | Lấy giá trị theo key |
removeItem(key) | Xóa một key |
clear() | Xóa tất cả |
key(index) | Lấy key tại vị trí index |
length | Số lượng item lưu trữ |
Ví dụ
<!DOCTYPE html>
<html>
<style>
body { color: #000; height: 100vh; background-color: #8BC6EC; background-image: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%) no-repeat; text-align: center; }
.btn { background: #db133a; border: none; height: 2rem; border-radius: 2px; width: 45%; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem auto; }
.show { font-size: 1.2rem; margin-top: 1rem; }
</style>
<body>
<h1>Demo sessionStorage</h1>
<button onclick="storeData()" class="btn">Lưu "Nguyễn Văn An"</button>
<button onclick="showData()" class="btn">Hiển thị dữ liệu</button>
<button onclick="clearData()" class="btn" style="background:#e74c3c">Xóa tất cả</button>
<div class="show"></div>
<script>
function storeData() {
sessionStorage.setItem('ho', 'Nguyễn');
sessionStorage.setItem('ten', 'Văn An');
document.querySelector('.show').innerHTML = '<p style="color:green">Đã lưu vào sessionStorage</p>';
}
function showData() {
var ho = sessionStorage.getItem('ho');
var ten = sessionStorage.getItem('ten');
document.querySelector('.show').innerHTML = 'Dữ liệu: ' + (ho || '') + ' ' + (ten || '');
}
function clearData() {
sessionStorage.clear();
document.querySelector('.show').innerHTML = '<p style="color:red">Đã xóa sessionStorage</p>';
}
</script>
</body>
</html>
Kết quả
- Nhấn "Lưu" → thông báo thành công.
- Nhấn "Hiển thị" → thấy "Nguyễn Văn An".
- Đóng tab → mở lại trang → dữ liệu đã mất (khác localStorage).
So sánh: localStorage bền vững (không hết hạn), sessionStorage chỉ trong tab. Cùng origin (domain+port+protocol). Dung lượng ~5-10MB.