JavaScript program to access browsing history


Following is the code to access browsing history in JavaScript −

Example

 Live Demo

<!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>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

On clicking the ‘BACKWARD’ button u would go to previous page in history −

Updated on: 17-Jul-2020

313 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements