21

I am refreshing some pages with AJAX and so an updating the history with the following code -

/** Update the page history */
var pushState_object = {
    ajax_string: ajax_string,
    security: security,
};
window.history.pushState(pushState_object, title, permalink);

I am then calling this onPopState function on page load -

window.onpopstate = function(e){
    if(window.history.state !== null){
        initiate_load_updated_page(window.history.state.ajax_string, window.history.state.security, 0)
    }
}

I am having a slight problem though using the back button when going from a page where the content was generated through AJAX to a page that was loaded in the usual way. The URL will change, but the page will not reload. Clicking back again takes me to the page before, as I would expect, and then going forward works fine - it is just that one situation where the back button does not work.

Any suggestions here would be appreciated.

pimvdb
  • 151,816
  • 78
  • 307
  • 352
David Gard
  • 11,225
  • 36
  • 115
  • 227

1 Answers1

19

The initial state does not have a .state property available, because you didn't use .pushState to add such data (it was loaded the normal way as you describe).

What you do know though, is that if there is no .state, it must be the original state, so you can use an else block like this: http://jsfiddle.net/pimvdb/CCgDn/1/.

Lastly, you can use e.state.

window.onpopstate = function(e){
    if(e.state !== null) { // state data available
        // load the page using state data
        initiate_load_updated_page(e.state.ajax_string, window.history.state.security, 0);

    } else { // no state data available
        // load initial page which was there at first page load
    }
}
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • 1
    Thanks for your replay, the way you explained it helped me understand the problem. Rather than use `else` suggested, I used `replaceState()` on the page when it was initially loaded to ensure that the correct `.state` existed. I did this because I'm really not sure how else I would have been able to reload the contents of the page through JS. Possibly not the most elegent way of doing it, but it works. Thanks for you assistence. – David Gard Oct 25 '11 at 13:35
  • 1
    @DavidGard can you please show how you solved this... I am having a similar problem and I'm not sure on how to use `replaceState()` for solving it – Nick Ginanto Mar 27 '13 at 06:38
  • @NickGinato - Wow, this was like a year and a half ago! I'll try and dig something out, but no promises. – David Gard Mar 28 '13 at 09:09
  • 6
    In the above solution, if anyone else is struggling, just change the initiate_load_updated_page line to location.reload(); Thanks. – harkirat1892 Jan 13 '16 at 12:23