Thuộc tính history.length trả về số lượng URL trong danh sách lịch sử duyệt web của cửa sổ hiện tại. Giá trị này bao gồm trang hiện tại.
Cú pháp
history.length
Ví dụ: Hiển thị độ dài lịch sử
<!DOCTYPE html>
<html>
<head>
<style>
body { text-align: center; font-family: sans-serif; padding: 20px; }
.btn {
background-color: #6f42c1; color: white; border: none;
padding: 10px 20px; border-radius: 5px; cursor: pointer;
font-size: 1rem; margin: 10px; display: inline-block;
}
.show {
font-size: 2rem; font-weight: bold; color: #fd7e14;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>Ví dụ History.length</h1>
<button onclick="showHistoryLength()" class="btn">Xem độ dài lịch sử</button>
<div id="result" class="show"></div>
<script>
function showHistoryLength() {
document.getElementById("result").textContent = history.length;
}
</script>
</body>
</html>
Kết quả
Trước khi nhấn nút:

Sau khi nhấn nút "Xem độ dài lịch sử":

⚠️ Lưu ý quan trọng:
- Giá trị tối thiểu là
1(trang hiện tại). - Không thể truy xuất URL cụ thể trong lịch sử do chính sách bảo mật (privacy).
- Chỉ có thể điều hướng:
history.back(),history.forward(),history.go(n). - API History hiện đại (
history.pushState(),replaceState()) thay đổi length nhưng không tải lại trang.