JavaScript·100 questions

How to work with the History API?

Answer

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

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

For navigating through history in code, the methods include history.back(), which takes the user one page back, history.forward(), which moves them forward, and the universal history.go(delta) method, where a numeric argument specifies how many steps forward or backward to move in the stack. When the user clicks the browser's navigation buttons or when go, back, or forward 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 according to the loaded section.

Was this answer helpful?

More questions in this topic

Related questions from other topics