JavaScript History
The history
object in JavaScript allows interaction with the browser's session history. It provides methods to navigate back, forward, or move to a specific page in the browsing history.
Key Topics
History Properties
The history
object includes the following property:
- length: Returns the number of entries in the session history for the current tab.
console.log("History Length:", history.length);
Output
> History Length: [Number of entries in the session history]
Explanation: The length
property of the history
object returns the count of entries in the session history.
History Methods
The history
object includes the following methods:
- back(): Navigates to the previous page in the session history.
- forward(): Navigates to the next page in the session history.
- go(n): Navigates to a specific page in the history, relative to the current page. A positive number moves forward, and a negative number moves backward.
// Go to the previous page
history.back();
// Go to the next page
history.forward();
// Go 2 pages back
history.go(-2);
// Go 1 page forward
history.go(1);
Explanation: The back
, forward
, and go
methods are used to navigate the session history programmatically.
JavaScript Usage in DOM
Below is a DOM-based example demonstrating the use of the history
object for navigation controls.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript History Example</title>
</head>
<body>
<button onclick="goBack()">Go Back</button>
<button onclick="goForward()">Go Forward</button>
<button onclick="goSpecific(-2)">Go Back 2 Pages</button>
<script>
// Navigate back
function goBack() {
history.back();
}
// Navigate forward
function goForward() {
history.forward();
}
// Navigate to a specific page
function goSpecific(steps) {
history.go(steps);
}
</script>
</body>
</html>
Key Takeaways
- Session History: The
history
object provides access to the session history. - Programmatic Navigation: Use methods like
back
,forward
, andgo
for navigation. - History Length: The
length
property reveals the number of entries in the session history. - User Experience: The
history
object enables seamless navigation within the browsing session.