views:

235

answers:

3

I have an AJAX app. A user clicks a button, and the page's display changes. They click the back button, expecting to go to the original state, but instead, they go to the previous page in their browser.

How can I intercept and re-assign the back button event? I've looked into libraries like RSH (which I couldn't get to work...), and I've heard that using the hash tag somehow helps, but I can't make sense of it.

Thank you!

A: 

I don't really know how to answer your question, but as an alternative you could provide your own back button and warn users not to use the one in their browser.

If you don't want to provide a way for the users to go back, you might have no choice but to warn them not to use it and then pray they're not silly enough to try.

I'm not really sure you can intercept back button events-- they've always struck me as being something the web browser provides, since it's the web browser that implements the list/stack mechanism allowing for an ordered traversal of the pages and since it's the web browser that caches the pages in order to make this process possible and relatively quick.

Platinum Azure
I already provide my own back button. People will act how they will act.
Zachary Burt
+1  A: 

Due to privacy concerns, it's impossible to disable the back button or examine the user's history, but it is possible to create new entries in this history without changing pages. Whenever your AJAX application changes state, update top.location with a new URI fragment.

top.location = "#new-application-state";

This will create a new entry in the browser's history stack. A number of AJAX libraries already handle all the boring details, such as Really Simple History.

Matthew
What other boring details do I need to take care of, besides setting top.location?
Zachary Burt
Since the "onload" event isn't triggered when the user clicks back, you need something to trigger an event. There are also some differences between browsers. A good AJAX library would encapsulate all these details, including the `setTimeout()` in darkporter's example.
Matthew
+6  A: 
darkporter
I'm not the poster, but this is very helpful..
Brendan Long
Also not the poster, but nice answer.
Dave Ray
Why thank you very much. This is excellent.
Zachary Burt