HTML5: Refresh page when popstate is fired

I have a ajax search-form like:

url: /search/

=> User enters a search-term and clicks a button

=> search is done and shows the results via ajax in a div on the page

But: I also want the user to be able to copy&paste the URL to friends and navigate through the previous searches. So when triggering the search, I change the url in the browsers addressbar from

/search/

to

/search/?q=yourkeyword

using:

window.history.pushState("", "Search for "+keyword, "/search/?q="+keyword);

This changes the url in the browsers addressbar to /search/?q=yourkeywords and works fine.

Now, hitting the back-button, the browsers addressbar is showing again /search/, which is fine. But the page-content is not reloaded, it still shows the results from /search/?q=yourkeyword.

So I added:

window.addEventListener("popstate", function(e) 
{   location.reload();
});

Is this the correct way? It works fine in desktop-browsers like FF and Chrome, but for example in iOS, the popstate-event is fired on the very first loading of searchform on /search/, resulting in a neverending reloading of that page.

Whats the right way to do it?


Solution 1:

The simplest solution is to set a global variable when you use pushState. Then, in your onpopstate handler just check if that is set. E.g.:

window.historyInitiated = true;
window.history.pushState("", "Search for "+keyword, "/search/?q="+keyword);
...
window.addEventListener("popstate", function(e) {
  if (window.historyInitiated) {
    window.location.reload();
  }
});

Solution 2:

My suggestion:

window.location.href = window.location.href;

I haven't tested it, but I think it will do what you want.