Skip to content

History object in JavaScript | API

  • by

JavaScript History object has the URLs visited by the user. This object allows you to access the history stack of the browser.

window.history 
// OR
history  

Note: The window part can be removed from the window object using the history object alone, which works fine.

History Object Properties and Methods

The history object provides three methods for navigating between pages in the history stack. (Lenght is property)

Property/MethodDescription
back()Loads the previous URL (page) in the history list
forward()Loads the next URL (page) in the history list
go()Loads a specific URL (page) from the history list
length(Property) Returns the number of URLs (pages) in the history list

History object in JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    history.pushState({page: 1}, "title 1", "?page=1")
    history.pushState({page: 2}, "title 2", "?page=2")

    console.log(window)

    let length = history.length;
    console.log(length)

    console.log(history.back()); //for previous page  
    console.log(history.forward()); //for next page  
    console.log(history.go(2)); //for next 2nd page  
    console.log(history.go(-2)); //for previous 2nd page  

  </script>
</body>
</html>

Output:

History object in JavaScript

Do comment if you have any doubts or suggestions on this JS window object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading