What You Need To Know About JavaScript Window History

Posted by TotalDC

Last time we covered JavaScript Window Location and now let’s continue by learning about JavaScript Window History.

The JavaScript History Object

The history object contains the browser session history – a list of all the pages visited in the current window. You can access it either by typing for example window.history.length or shorter version – history.length. In this article, you will learn how to get the information of a user’s browsing history. Keep in mind that for security reasons scripts are not allowed to access the stored URLs.

How To Get The Number Of Pages Visited In JavaScript

For this, you can use window.history.length property. It will get you the number of pages in the session history of the browser for the current window. It also includes the currently loaded page.

You can use this property to find out how many pages a user has visited during the current browser session, just like in the example:

<script>
function getViews() {
    console.log("You've accessed " + history.length + " web pages in this session.");
}
</script>
 
<button type="button" onclick="getViews();">Get Views Count</button>

How To Go Back To The Previous Page In JavaScript

For this, you can simply use the back() method of the history object – history.back(). It is the same as clicking the browser’s back button. Here’s an example for you:

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

How To Go Forward To The Next Page In JavaScript

For this you can simply use the forward() method of the history object – history.forward(). It is the same as clicking the browser’s forward button. Here’s an example for you:

<script>
function goForward() {
    window.history.forward();
}
</script>
 
<button type="button" onclick="goForward();">Go Forward</button>

How To Go To A Specific Page In JavaScript

You are not limited with back and forward movement through pages, you can load a specific page from the session history by using go() method, which syntax looks like this – history.go(). This method takes an integer as a parameter. A negative integer moves backward in history and a positive integer moves forward in history. Here’s how it looks:

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

Keep in mind, if you attempt to access the page that does not exist in the window’s history then the methods back()forward() and go() will simply do nothing.