The history object in Javascript is part of the Browser Object Model (BOM) and provides an interface for manipulating the browser's session history.
It allows us to navigate `forward` and `backward` in the browsing history stack and control the behaviour of the browser's `back` and `forward` buttons.
Returns the number of URLs in the browser history stack.
console.log("Number of browser history stack: ", history.length);
history.back();
Navigate to the previous page or URL in the browser history stack.
history.forward();
// Go back three pages history.go(-3); // Go forward four pages history.go(4);
Navigate to the next page or URL in the browser history stack.
history.pushState({ page: 5 }, "Title", "/page-5");
Navigate a specific page or URL from the browser history stack based on the number passed as an argument to `history.go(integerValue)`. The number argument can be positive (forward) or negative (backward).
window.addEventListener('popstate', function(event) { console.log("Location changed:", document.location, event.state); });
we can change the current URL without triggering a page reload using the `history.pushState(stateObject, title, url)` method and it also add a new URL in browser history stack as well.
This method adds a new entry to the session history and changes the URL to the specified one.
The popstate event is fired when the active history entry changes.
This event is useful for handling changes in the browser's history using the back or forward buttons.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>History Object Example</title> </head> <body> <button onclick="goBack()">Go Back</button> <button onclick="goForward()">Go Forward</button> <button onclick="changeLocation()">Change Location</button> <script> function goBack() { history.back(); } function goForward() { history.forward(); } function changeLocation() { history.pushState({ page: 4 }, "New Page", "/new-page-4"); } window.addEventListener('popstate', function(event) { console.log("Location changed:", document.location, event.state); }); </script> </body> </html>