I've search on google and some other questions in this forum, but it seems not answered my question.

Based on MDN https://developer.mozilla.org/en-US/docs/Web/API/window.onpopstate :

Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by doing a browser action such as a clicking on the back button (or calling history.back() in JavaScript). And the event is only triggered when the user navigates between two history entries for the same document.

Im looking for onpopstate alternative that has the same functional as window.onhashchange (https://developer.mozilla.org/en-US/docs/Web/API/Window.onhashchange) that will fire the event when the url changed.

Would you like to share your solution?

有帮助吗?

解决方案

I think you probably could use the "History.js" tool, which provides a "statechange" event that you can listen for. The tool fires that event either when the forward/backward buttons are pressed or when you use pushState/replaceState.

https://github.com/browserstate/history.js/

Of course, now you've traded for a different problem, which is that you have the event being fired for both types of actions, and you often want to distinguish between them and that's more difficult. So you have to hack your own solution to distinguishing them. Most people seem to set some global flag whenever they are about to call pushState/replaceState, and then check for this flag in the event handler. If the flag is set, then the event came from your own code, if not, it came from the browser buttons.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top