I’m using history.pushState to change the URL programmatically without any user interaction (like a button click). This works fine in Chrome and some other browsers, but in Firefox, when I press the browser back button, the popstate event is not firing as expected.
Expected behavior:
- The URL should change to /new-url after page load.
- When the user presses the browser back button, the popstate event should fire.
Actual behavior in Firefox:
- The URL changes correctly.
- Pressing the back button does not trigger popstate.
- No errors in the console.
Here’s a simplified version of the code:
`window.addEventListener(‘load’, () => {
history.pushState({ page: 1 }, ”, ‘/new-url’);
});
window.addEventListener(‘popstate’, (event) => {
console.log(‘Popstate fired:’, event.state);
});`
What I’ve tried:
- Wrapping pushState in setTimeout
- Ensuring DOM is fully loaded
- Triggering pushState from inside DOMContentLoaded
- Using replaceState before pushState
- Still, the issue persists only in Firefox.
Question :
Is this a known Firefox behavior/limitation when using pushState without user interaction?
Is there a workaround to reliably trigger the popstate event in this scenario?
Any help or explanation would be appreciated!