techStackGuru

JavaScript History


The History object is referenced via the Window objects history property. It has a list of all the pages visited in the current frame or window, as well as the browser session history.


  • length - Used to retrieve the total number of pages in the browsers session history for the current window
MethodDescriptionExample
forward()Next page is loadedhistory.forward()
back()Previous page is loadedhistory.back()
go()Specific page number is loadedhistory.go(5)

Check current browser session


<!DOCTYPE html>
<html lang="en">
<body>

 <script>
    function show() {
        alert(history.length + " current browser session");
    }
 </script>

<button type="button" onclick="show();">Show</button>
</body>
</html>

Next Page


<script>
  function nextPage() {
    window.history.forward();
  }
</script>
 
<button type="button" onclick="nextPage();">Next</button>

Previous Page


<script>
  function previousPage() {
    window.history.back();
  }
</script>
 
<button type="button" onclick="previousPage();">Back</button>

Specific Page


window.history.go(2);   // Go forward two pages
window.history.go(4);   // Go forward four pages
window.history.go(-2);  // Go back two pages
window.history.go(-4);  // Go back four pages
window.history.go(0);   // Reload the current page


previous-button
next-button