In an HTML document, the history.pushState()
method adds an entry to the browser's session history stack.
This method is asynchronous. Add a listener for the popstate
event in order to determine when the navigation has completed. The state
parameter will be available in it.
pushState(state, unused)
pushState(state, unused, url)
In a sense, calling pushState()
is similar to setting window.location = "#foo"
, in that both will also create and activate another history entry associated with the current document. But pushState()
has a few advantages:
- The new URL can be any URL in the same origin as the current URL. In contrast, setting
window.location
keeps you at the same document only if you modify only the hash. - Changing the page's URL is optional. In contrast, setting
window.location = "#foo";
only creates a new history entry if the current hash isn't #foo
. - You can associate arbitrary data with your new history entry. With the hash-based approach, you need to encode all of the relevant data into a short string.
Note that pushState()
never causes a hashchange
event to be fired, even if the new URL differs from the old URL only in its hash.
This creates a new browser history entry setting the state and url.
const state = { page_id: 1, user_id: 5 };
const url = "hello-world.html";
history.pushState(state, "", url);
const url = new URL(location);
url.searchParams.set("foo", "bar");
history.pushState({}, "", url);