The browser remembers all visited urls in a browsing session. A user can use back / forward buttons to manually navigate to urls from the history.

The history can be accessed programmatically via window.history.

For security reasons we can't read what urls are in the history. We don't want a website to see what pages the user visited before.

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 number of entries in history.

To navigate to a given entry use history.go(n). history.go(-1) is an equivalent of history.back() and history.go(1) is the same as history.forward().

history.pushState, history.replaceState

You can add new entries to history with history.pushState(state_object, title, url), for example:

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

history.replaceState(state_object, title, url) is like pushState except it replaces current state instead of adding a new one, e.g.:

var stateObj = { foo: "bar" };
window.history.pushState(stateObj, "a page bar", "/foo/bar.html");

State object can be any serializable JavaScript value.

Manually adding to history is useful when implementing custom UI interactions. For example an implementation of infinite scroll might add checkpoints to navigation history so that back button navigates to a meaningful place in the page.

window.onpopstate

Navigation (either manual with back / forward button or programmatically via back(), forward(), go() triggers onpopstate event:

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

Event is of PopStateEvent type with the following properties: