Junior
Kuidas JavaScriptis saab hallata brauseri ajalugu, liikudes edasi ja tagasi?
sobes.tech AI
Vastus AI-lt
history objekt provides access to the browser's session history. Main methods for management:
history.back(): moves back one page in the history.history.forward(): moves forward one page in the history.history.go(delta): moves by the specified number of steps in the history (deltacan be negative to go back).
Example of usage:
// Return to the previous page
history.back();
// Move to the next page
history.forward();
// Move back two pages
history.go(-2);
// Move forward three pages
history.go(3);
The history object also allows managing the history state without page reloads, using pushState and replaceState methods.
history.pushState(state, title, url): adds a new state to the session history.state: the state object associated with the history entry.title: the page title (most browsers ignore this).url: the URL associated with the history entry.
history.replaceState(state, title, url): replaces the current state in the session history.
Example with pushState:
// Add a new state to the history
history.pushState({ page: 1 }, "Page 1", "/page1");
// Further actions on the page without full reload
// When the user presses the "back" button, a popstate event will fire
window.addEventListener('popstate', function(event) {
console.log('State changed:', event.state); // { page: 1 }
// Update page content according to the state
});
Example with replaceState:
// Replace the current state in the history
history.replaceState({ tab: 'active' }, "Active tab", "/active-tab");
The popstate event fires when a session history entry is activated.