Demystifying JavaScript history.back() and history.go() methods

on in AJAX and Fetching Data
Last modified on

One of my clients needed his online shop customers to be able to go back several steps with one click and keep the current session variables in memory. The obvious solution was the browser’s back button. But I couldn’t instruct the customer to click it one time or 3 times or 5 times. So, I chose to add a link with a JavaScript history object.

back()⁣ – Go to the previous URL entry in the history list. This does the same thing as the browser’s back button.

forward()⁣ – Go to the next URL entry in the history list. This does the same thing as the browser’s forward button. This is only effective when there is a next document in the history list. The back function or browser’s back button must have previously been used for this function to work.

go(position)⁣ – This function will accept an integer or a string. If an integer is used, the browser will go forward or back (if the value is negative) the number of specified pages in the history object (if the requested entry exists).

<a href="javascript:history.back()">Go back</a>


<a href="javascript:history.go(-3)">Go back to step X</a>

The back() and go() methods are supported in all major browsers.

History is one of the sub-objects of Windows, and an interface to the history stored by your browser. Properties and methods apply to the object history of windows or to each frame in the window.

history.go(0) acts like pressing the reload button.

The length property returns the number of URLs in the history list.

Note: Internet Explorer and Opera start at 0, while Firefox, Chrome, and Safari start at 1.

console.log("Number of URLs in history list: " + history.length);

Related posts