Session history state and popstate
Quick answer
The History API can add or replace a session-history entry without loading a new document. It allows a client application to connect its view state to Back and Forward navigation.
How it works
history.pushState(state, unused, url?) adds an entry; replaceState changes the current entry. The second argument is traditionally an empty string. URL changes must satisfy document URL rewrite restrictions, including same-origin rules for HTTP(S) documents. State must be serializable and is not an arbitrary live object reference. popstate is dispatched on applicable history traversal, not simply from pushState or replaceState.
Local examples
Run in a fresh browser document; no external network is needed. The actual ByteMind editor is unverified.
(async () => {history.replaceState({page:2},"");console.log(history.state.page);})()Expected console output:
2Replacing the current entry sets its state without a network request.
Run in a fresh browser document; no external network is needed. The actual ByteMind editor is unverified.
(async () => {let calls=0;window.addEventListener("popstate",()=>calls++);history.pushState({page:3},"");console.log(history.state.page,calls);})()Expected console output:
3 0pushState does not itself dispatch popstate.
Common mistakes
Do not store secrets or large data in history state. Reconstruct view state during traversal; pushing an entry does not itself trigger popstate.
Guided practice
On a local test page, push two entries, use Back, and restore the selected item from event.state.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Session history state and popstate — Knowledge Check
Apply the concept and reason about the example output.
Which method adds a session-history entry?
What is the typical second argument to pushState?
Does pushState itself dispatch popstate?
What is the expected console output of Session history state and popstate example 1?
(async () => {history.replaceState({page:2},"");console.log(history.state.page);})()What is the expected console output of Session history state and popstate example 2?
(async () => {let calls=0;window.addEventListener("popstate",()=>calls++);history.pushState({page:3},"");console.log(history.state.page,calls);})()