PopState Event
PopState Event
Section titled “PopState Event”Introduction
Section titled “Introduction”The popstate event fires when the user navigates backward or forward using the browser’s back/forward buttons.
Basic Usage
Section titled “Basic Usage”// Listen for back/forward navigationwindow.addEventListener('popstate', (event) => { if (event.state) { console.log('Navigated to:', event.state); updateContent(event.state); }});Important Note
Section titled “Important Note”// pushState does NOT fire popstatehistory.pushState({ page: 1 }, '', '/page1');// No popstate event fired
// Only browser back/forward triggers popstate// Going back: popstate fires with { page: 1 }State Object
Section titled “State Object”// The state object passed to pushState/replaceState is available in popstatewindow.addEventListener('popstate', (e) => { const state = e.state; // null if no state was set if (state) { console.log('Page:', state.page); }});Summary
Section titled “Summary”popstatefires on browser back/forward navigation- Does NOT fire on
pushState()orreplaceState() - Event contains the state object from the history entry
- Essential for handling SPA navigation