History of visited URLs

suggest change

The browser remembers the URLs visited in a browsing session. The back and forward buttons move through that history.

Scripts can navigate with window.history. They cannot read the URLs in the history. A page must not be able to see where the user has been.

history.back, history.forward, history.go, history.length

You can navigate the history with window.history.back() and window.history.forward().

Use history.length to get the number of entries in the session history, including the current page.

history.go(n) moves by n entries. history.go(-1) is equivalent to history.back(), and history.go(1) is the same as history.forward(). history.go(0) reloads the current page.

history.pushState, history.replaceState

You can add an entry with history.pushState(state, title, url). Browsers ignore title. A URL, if you pass one, must be same-origin. For example:

window.history.pushState("arbitrary object", "a title", "/example/path.html");

history.replaceState(state, title, url) replaces the current entry instead of adding one:

const stateObj = { foo: "bar" };
window.history.replaceState(stateObj, "", "/foo/bar.html");

The state must be structured-cloneable. Functions and DOM nodes are not. pushState and replaceState do not fire popstate.

Adding history entries is useful for custom navigation. An infinite-scroll page can record checkpoints so that Back returns to a meaningful place on the page.

window.onpopstate

Back, forward, and history.go() fire popstate. pushState does not:

window.onpopstate = (event) => console.log("event:", event)

Event is of PopStateEvent type with the following properties:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents