Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Truy cập lịch sử duyệt web (History API) trong JavaScript


Đối tượng window.history cho phép điều hướng lịch sử phiên bản: length (số lượng entry), back(), forward(), go(n). Lưu ý: Không thể đọc URL thực tế trong history vì lý do bảo mật.

Ví dụ

Hiển thị độ dài history, nút Quay lại / Tiến tới:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>History API</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 18px; font-weight: 500; color: rebeccapurple; }
  </style>
</head>
<body>
  <h1>Truy cập lịch sử duyệt web (History API)</h1>
  <div class="result"></div>
  <button class="Btn">XEM LỊCH SỬ</button>
  <h3>Nhấn để xem history.length</h3>
  <button class="Btn">TIẾN TỚI</button>
  <button class="Btn">QUAY LẠI</button>
  <h3>Nhấn để điều hướng lịch sử</h3>
  <script>
    const resEle = document.querySelector(".result");
    const btns = document.querySelectorAll(".Btn");
    btns[0].addEventListener("click", () => resEle.textContent = `history.length = ${window.history.length}`);
    btns[1].addEventListener("click", () => window.history.forward());
    btns[2].addEventListener("click", () => window.history.back());
  </script>
</body>
</html>

Kết quả

Nhấn "XEM LỊCH SỬ" -> hiển thị số lượng entry. "QUAY LẠI" / "TIẾN TỚI" điều hướng tương tự nút back/forward trình duyệt.

Mở rộng: history.pushState(), replaceState() dùng cho SPA (Single Page Application) để quản lý URL không reload trang.