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 :)