The popstate event
Learn to catch the popstate event fired on back/forward navigation.
The popstate event
When the user clicks the back or forward button (or code calls history.back()), the browser fires a popstate event. You listen for it on window.
window.addEventListener('popstate', (event) => {
console.log(event.state);
});event.state holds the state object of the new active entry, if any. pushState and replaceState do not fire this event; only back or forward navigation does.
Listening and state
Inside a popstate listener you read event.state to access the state of the new active entry. In SPAs this is used to restore the view during back or forward navigation.
window.addEventListener('popstate', (event) => {
if (event.state) {
render(event.state.path);
}
});On the first load event.state is usually null, so checking first is a good habit.
Exercise Add a popstate listener
Add a 'popstate' event listener to the window object. The listener should be an arrow function that logs event.state with console.log.
Show example solution
window.addEventListener('popstate', (event) => {
console.log(event.state);
});
Test yourself
-
Match the popstate concepts
- popstate
- back or forward event
- event.state
- the entry state
- pushState
- does not fire popstate
- window
- the event target
-
Add a popstate listener
____, (event) => { console.log(event.state); });Show answer
window.addEventListener('popstate', (event) => { console.log(event.state); }); -
When does the popstate event fire?
- When pushState is called
- When replaceState is called
- When the page first loads
- When the back or forward button is pressed
Show answer
When the back or forward button is pressed — Correct! popstate fires on back or forward navigation.