Sau đây là mã để truy cập lịch sử duyệt web trong JavaScript -
Ví dụ
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</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>Program to access browsing history</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to see history length</h3>
<button class="Btn">FORWARD</button>
<button class="Btn">BACKWARD</button>
<h3>Click on the above button to go forward or backward</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelectorAll(".Btn");
BtnEle[0].addEventListener("click", () => {
resEle.innerHTML = window.history.length;
});
BtnEle[1].addEventListener("click", () => {
window.history.forward();
});
BtnEle[2].addEventListener("click", () => {
window.history.back();
});
</script>
</body>
</html> Đầu ra
Đoạn mã trên sẽ tạo ra kết quả sau -
Khi nhấp vào nút 'BẤM VÀO ĐÂY' -
Khi nhấp vào nút "QUAY LẠI", bạn sẽ chuyển đến trang trước trong lịch sử -