The window.history object contains the URLs that the user has visited in the current browser window. For privacy reasons, you cannot see exactly *which* URLs are in the list, but you can use JavaScript to navigate backward and forward through them.
These buttons simulate the standard browser "Back" and "Forward" buttons using pure JavaScript:
The history.back() method loads the previous URL in the history list. It works exactly like clicking the back arrow in your browser.
function goBack() {
window.history.back();
}
The history.forward() method loads the next URL in the history list. This only works if the user has already navigated back at least once.
function goForward() {
window.history.forward();
}
If you want to move multiple steps at once, you can use the go() method. It accepts a positive or negative integer representing how many steps to move.
// Go back 2 pages
window.history.go(-2);
// Refresh the current page
window.history.go(0);
// Go forward 1 page (same as history.forward())
window.history.go(1);
history.go(-1) is functionally identical to history.back().
You can check how many entries are in the current session's history stack using the length property.
let entriesCount = history.length;
console.log("History entries: " + entriesCount);
| Method | Action |
|---|---|
history.back() |
Navigates to the previous page in history |
history.forward() |
Navigates to the next page in history |
history.go(n) |
Navigates 'n' steps forward or backward |
history.length |
Returns the number of URLs in the history record |
pushState and replaceState.