Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Page not reloading via 'back' when using pushState() / onpopstate

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.

like image 427
David Gard Avatar asked Oct 25 '11 11:10

David Gard


People also ask

Does history pushState reload page?

The history. pushState() method can be used to push a new entry into the browser's history—and as a result, update the displayed URL—without refreshing the page. It accepts three arguments: state , an object with some details about the URL or entry in the browser's history.

What triggers Onpopstate?

The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history. back() or history. forward() in JavaScript). Browsers tend to handle the popstate event differently on page load.

What is the difference between pushState and replaceState?

The big difference is, that while pushState will create a new entry in the browser's history, replaceState will only replace the current state. As a side effect of this, using the replaceState method will change the URL in the address bar, without creating a new history entry.


1 Answers

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
    }
}
like image 173
pimvdb Avatar answered Nov 15 '22 16:11

pimvdb