JavaScript·100 questions

QUESTION: Как работать с history API?

Answer

Working with the History API in JavaScript allows web developers to programmatically manage the browser's session history, which is the contents of the history stack of the current tab. This is critically important for creating modern single-page applications (SPAs), where transitions between sections occur without a full page reload, while the user still expects familiar interface behavior with working browser forward and back buttons.

The primary method for changing the history without a reload is history.pushState(state, title, url). This method accepts three arguments: the state object, which contains data bound to that state; the page title, which is ignored by most modern browsers; and the new URL, which is displayed in the browser's address bar. If you need to modify the current entry rather than add a new one, the history.replaceState() method is used, which overwrites the current state and address.

For navigating through history in code, the API provides history.back(), which takes the user back one page, history.forward(), which moves forward, and the universal history.go(delta) method, where the numeric argument specifies how many steps forward or backward to shift in the stack. When the user clicks the browser's navigation buttons or when the go, back, or forward methods are called, the popstate event fires on the window object. In the handler for this event, the developer can retrieve the current state via event.state and redraw the application interface to match the loaded section.

Was this answer helpful?

More questions in this topic

Related questions from other topics