Skip to content Skip to sidebar Skip to footer

Chrome Popstate Not Firing On Back Button If No User Interaction

I'm trying to use 'pushState' and the 'popstate' event to trap Back button navigation, however, while the popstate event triggers correctly in Firefox, it doesn't trigger in Chrome

Solution 1:

Try adding a setTimeout of 0

window.onpopstate = () =>setTimeout(alert.bind(window, "Pop"), 0);

When writing functions that process popstate event it is important to take into account that properties like window.location will already reflect the state change (if it affected the current URL), but document might still not. If the goal is to catch the moment when the new document state is already fully in place, a zero-delay setTimeout() method call should be used to effectively put its inner callback function that does the processing at the end of the browser event loop: window.onpopstate = () => setTimeout(doSomeThing, 0);

Content is taken from https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event

On a sidenote it is advised not to use this as browsers may remove this any time.

Solution 2:

As others suggested in comment, this should be by design of browser software to prevent hijacking of its default back button behavior.

Post a Comment for "Chrome Popstate Not Firing On Back Button If No User Interaction"