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

安稳与你 提交于 2019-12-18 14:47:48

问题


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.


回答1:


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
    }
}


来源:https://stackoverflow.com/questions/7888711/page-not-reloading-via-back-when-using-pushstate-onpopstate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!