pushState & replaceState
pushState & replaceState
Section titled “pushState & replaceState”Introduction
Section titled “Introduction”pushState adds a new entry to the history stack, while replaceState modifies the current entry without adding a new one.
pushState
Section titled “pushState”// Add new history entryhistory.pushState({ page: 1 }, 'Page 1', '/page1');
// Arguments:// { page: 1 } — state object (can be retrieved later)// 'Page 1' — title (mostly ignored by browsers)// '/page1' — URL to display in address bar (must be same origin)replaceState
Section titled “replaceState”// Replace current history entry (doesn't add to stack)history.replaceState({ page: 2 }, 'Page 2', '/page2');Key Notes
Section titled “Key Notes”pushStatedoes NOT firepopstateeventpushStatedoes NOT actually load the new URL- The URL must be same-origin (can’t push cross-origin URLs)
- State objects can be retrieved via the
popstateevent
Summary
Section titled “Summary”pushState()— adds a new history entryreplaceState()— modifies the current entry- Both accept state, title, and URL
- Neither actually loads the new page (ideal for SPAs)