问题
I have to maintain a site with an AJAX search form (for lets say books) and I want the search results to be a part of the browser history.
So I set the "popstate" event handler
window.addEventListener('popstate', function(e) {
alert("popstate: " + JSON.stringify(e.state));
});
and call pushState() upon the successfull AJAX request:
var stateObj = { q: "harry potter" };
window.history.pushState(stateObj, "Result", "/search");
Then my clickflow is:
- Load the page with the search form - NORMAL request - path is /
- Enter a query string and submit the form - AJAX request - path changes to /search
- Click on a search result - NORMAL request - path changes to /books/harry-potter
- When I now go back by clicking the browser back button I would expect the "popstate" event to be triggered with the according state object. But nothing happens. - path changes to /search
When I then go back one more time I get an alert with
popstate: null
- path changes to /And when I go forward after that, I get
popstate: {"q":"harry potter"}
- path changes to /search
So, the important popstate event (the one with the query string) gets only triggered when going forward, but not when going back.
Is this because im navigating back from a site, whose history entry has been created automatically instead of programmatically by pushState? But if so, the History API would only make sense for complete single page applications.
Behaviour is the same in any browser. Hope you can help me out :)
回答1:
For anyone wanting a little more explanation as to why the popstate event only occurs in certain scenarios, this helped me:
On the MDN popstate event page it states:
A popstate event is dispatched to the window each time the active history entry changes between two history entries for the same document.
and
The popstate event is only triggered by performing a browser action, such as clicking on the back button (or calling history.back() in JavaScript), when navigating between two history entries for the same document.
So it looks like popstate is only called when navigating to different urls within the same document. This works great for SPAs but not for anything else.
As an additional note, the html5 spec for session history doesn't seem to have much clarity as to when the popstate event is called:
The popstate event is fired in certain cases when navigating to a session history entry.
Which may indicate that different browsers will treat it differently.
I would love more insight from anyone else
来源:https://stackoverflow.com/questions/48912761/html5-history-api-popstate-not-called-when-navigating-back-from-another-page