The popstate Event: Detecting Back/Forward Navigation
What you'll learn: How to listen for and respond when users click the browser's back or forward buttons after you've used the History API.
What is the popstate Event?
When you use pushState() or replaceState() to change the URL, you're creating navigation history entries. But what happens when users click the back or forward buttons? That's where the popstate event comes in.
The popstate event fires whenever the active history entry changes between two entries you created with the History API. Think of it as a notification system: "Hey, the user just moved to a different state in your app's history!"
How It Works
The browser triggers popstate on the window object when:
- Users click the back button
- Users click the forward button
- You call
history.back()orhistory.forward()programmatically
Important: popstate does not fire when you call pushState() or replaceState(). Those methods change history silently. The event only fires for navigation between existing entries.
Listening for popstate
window.addEventListener('popstate', (event) => {
console.log('User navigated!');
console.log('State data:', event.state);
});
The event object includes a state property containing whatever state object you stored with pushState() or replaceState(). If the user navigates to an entry with no state, event.state will be null.
Why This Matters
Without listening to popstate, your back/forward buttons won't work properly in single-page applications. The URL might change, but your page content won't update to match. This event lets you detect the navigation and update your UI accordingly.
Key Takeaway: The popstate event fires when users navigate using back/forward buttons, giving you the state data you stored and allowing you to update your page to match the current history entry.