Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 802
Werner Avatar asked Feb 19 '15 08:02

Werner


3 Answers

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();
  }
});
like image 193
troelskn Avatar answered Oct 17 '22 02:10

troelskn


My suggestion:

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

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

like image 33
Dan Goodspeed Avatar answered Oct 17 '22 03:10

Dan Goodspeed


News from the year 2022

This problem resolved when all major browsers started to not emit popstate events on page load. So it should be relatively safe now to simply do:

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

All major browsers now

  • always trigger a popstate event when the user navigates (e.g. via back and forward buttons) to a history entry that was added via pushState()
  • never trigger a popstate when a webpage is loaded (e.g. via refresh button)

Quote from https://developer.mozilla.org/en-US/docs/Web/API/PopStateEvent :

Note: Browsers used to handle the popstate event differently on page load, but now they behave the same. Firefox never emitted a popstate event on page load. Chrome did until version 34, while Safari did until version 10.0.

like image 1
Jan Feldmann Avatar answered Oct 17 '22 02:10

Jan Feldmann