How to reload page when back is pressed, after a pushState?

David Lawrence picture David Lawrence · Jul 31, 2012 · Viewed 10.4k times · Source

Im currently using Code Igniter to have pretty URLs, and I have this system that basically uses ajax to allow you to search for gyms.

Im using push state after a list of gyms is loaded, like this:

example.com/list/search_key/pagination-page/sort-by/filters~seperated~by~that

Where search_key is the city, state, or neighborhood in the area they want to search gyms, and filters are individual checkboxes.

What happens, is I use .ajax to send the search key and each individual checkbox value (either 1 or 0) through post, then code igniter uses the POST data and PHP, to generate a url like the one above. The ajax success push states the URL to be the one the PHP generated.

The problem is, that if you use say pagination to go to page-2, and you want to go to page-1, naturally youre going to use the browsers back button. The problem is, that it only backs the URL address bar to the url before hte current one, it doesnt actually change the pages content. I need it to either reload the page using the old (previous) url, or refresh, or something.

I can even use ajax to resubmit the form using the URL data, but I have no clue how to do this.

I have tried a few things, but nothing works at all. Pretty much I've tried everything on the first page of google, and everything seems promising but nothing actually works.

Is there anyway to refresh the page, if a pushstate url changes to a previous url?

PS Heres some of the key things Ive tried:

<script type="text/javascript">
$(window).unload(function(e){
   e.preventDefault();
   alert("Back was pressed!");
});
// If this wouldve worked, it wouldve atleast alerted me that.

// The code off this URL: http://www.mrc-productivity.com/techblog/?p=1235

// Some of the codes off this URL: http://forum.jquery.com/topic/howto-force-page-reload-refresh-of-previous-page-when-back-button-is-pressed

// A few others.
</script>

Answer

Derek Hunziker picture Derek Hunziker · Jul 31, 2012

Since you are pushing the state from your ajax success method, you can detect the back button using the window.onpopstate method.

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 click on the back button (or calling history.back() in JavaScript).

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");

window.onpopstate = function(event) {
    if(event && event.state) {
        // event.state.foo
    }
}