The history object gives a page controlled access to the current tab's session history. It can move backward or forward, report the number of history entries, and support same-document application state with pushState() and replaceState().
history.back();
history.forward();
history.go(-2);
history.length reports the number of entries in the current session history, including the current page. It does not reveal the URLs of those entries.
console.log(history.length);
Value in this tab:
history.back(); // Same idea as the browser Back button
history.forward(); // Move one step forward when possible
history.go(-2); // Move two entries back
history.go(1); // Move one entry forward
Out-of-range history navigation simply has no visible effect. You can also read how an HTML back button can return to the previous page.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>History object demo</title>
</head>
<body>
<p id="historyCount"></p>
<button type="button" id="forwardButton">forward</button>
<button type="button" id="backButton">Back</button>
<button type="button" id="goMinus1">go -1</button>
<button type="button" id="goMinus2">go -2</button>
<script>
const count = document.getElementById('historyCount');
count.textContent = `Total number of pages in History ${history.length}`;
document.getElementById('forwardButton').addEventListener('click', () => history.forward());
document.getElementById('backButton').addEventListener('click', () => history.back());
document.getElementById('goMinus1').addEventListener('click', () => history.go(-1));
document.getElementById('goMinus2').addEventListener('click', () => history.go(-2));
</script>
</body>
</html>
Modern applications can add or update same-document history entries without forcing a full page load. pushState() adds an entry; replaceState() updates the current entry. Navigating to those state entries can fire popstate.
history.pushState({ page: 2 }, '', '?page=2');
window.addEventListener('popstate', (event) => {
console.log(event.state);
});
The URL passed to pushState() or replaceState() must stay within the same origin. These methods are useful for interfaces such as single-page applications where visible content changes without a traditional full-page navigation.
go()?Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| jesi | 07-10-2012 |
| its working well!..... | |
| balu | 13-06-2014 |
| it was really help full if u guys provide little bit in depth explanations how the above code works thanks for your valuable information. | |
15-11-2023 | |
| Good | |