Search code examples
javascriptjquerybackbrowser-historyjquery-load

jQuery's load feature, doesn't allow back button?


I'm developing a social networking website and intend to make it as dynamic as possible. The only major problem I've come across so far is the inability to use the browsers back button when using jQuery's load function.

I've added the following code to actually change the users URL when the javascript function is used:

var stateObj = { foo: page };
history.pushState(stateObj, page, page);

I assumed that would work as I wanted it to, but unfortunately the URL changes but the content of the page stays as it is.

Does anyone know how I can have it load the last page visited? Not dynamically, just normally like any normal back button would work.

If you'd like an example of what's actually happening you can visit the temporary URL: http://goo.gl/0BOUV
You'll need to login, so here's some login details:
Email: [email protected]
Password: password


Solution

  • If you use pushState to change the displayed URL, then when the user presses "back", the browser doesn't reload the URL directly. Instead, it triggers an onpopstate event. See the Mozilla docs for details. You need to write a handler for that event that reloads the appropriate page based on the state data.

    Incidentally, pushState is a new HTML5 feature, so is not available in all browsers. The History.js library @Blender mentions provides a nice cross-browser compatibility layer. Even with the library, you still need to handle the state change event for when the user uses the back button.