How do you use `window.history` API?
TL;DR
The window.history
API allows you to manipulate the browser's session history. You can use history.pushState()
to add a new entry to the history stack, history.replaceState()
to modify the current entry, and history.back()
, history.forward()
, and history.go()
to navigate through the history. For example, history.pushState({page: 1}, "title 1", "?page=1")
adds a new entry to the history.
Using the window.history
API
The window.history
API provides methods to interact with the browser's history stack. This can be useful for single-page applications (SPAs) where you want to manage the URL and browser history without causing a full page reload.
Methods
history.pushState()
This method adds a new entry to the history stack.
- The first parameter is a state object associated with the new history entry.
- The second parameter is the title of the new history entry (currently ignored by most browsers).
- The third parameter is the URL to be displayed in the address bar.
history.replaceState()
This method modifies the current history entry.
- The parameters are the same as
pushState()
, but this method replaces the current entry instead of adding a new one.
history.back()
This method moves the user back one entry in the history stack, similar to clicking the browser's back button.
history.forward()
This method moves the user forward one entry in the history stack, similar to clicking the browser's forward button.
history.go()
This method moves the user a specified number of entries in the history stack.
Example
Here's a simple example demonstrating the use of pushState
and replaceState
: