Intercepting Call to the Back Button in My Ajax Application

Intercepting call to the back button in my AJAX application

Ah, the back button. You might imagine "back" fires a JavaScript event which you could simply cancel like so:

// this does not work
document.onHistoryGo = function() { return false; }

No so. There simply is no such event.

If you really do have a web app (as opposed to just a web site with some ajaxy features) it's reasonable to take over the back button (with fragments on the URL, as you mention). Gmail does this. I'm talking about when your web app in all in one page, all self-contained.

The technique is simple — whenever the user takes action that modifies things, redirect to the same URL you're already on, but with a different hash fragment. E.g.

window.location.hash = "#deleted_something";
...
window.location.hash = "#did_something_else";

If the overall state of your web app is hashable, this is a great place to use a hash. Say you have a list of emails, maybe you'd concatenate all their IDs and read/unread statuses, and take an MD5 hash, using that as your fragment identifier.

This kind of redirect (hash only) doesn't try to fetch anything from the server, but it does insert a slot in the browser's history list. So in the example above, user hits "back" and they're now showing #deleted_something in the address bar. They hit back again and they're still on your page but with no hash. Then back again and they actually go back, to wherever they came from.

Now the hard part though, having your JavaScript detect when the user hit back (so you can revert state). All you do is watch the window location and see when it changes. With polling. (I know, yuck, polling. Well, there's nothing better cross-browser right now). You won't be able to tell if they went forward or back though, so you'll have to get creative with your hash identifiers. (Perhaps a hash concatenated with a sequence number...)

This is the gist of the code. (This is also how the jQuery History plugin works.)

var hash = window.location.hash;
setInterval(function(){
if (window.location.hash != hash) {
hash = window.location.hash;
alert("User went back or forward to application state represented by " + hash);
}
}, 100);

Browser Back Button Handling in Ajax Based Application

You could use the RSH (reallysimplehistory) javascript library: http://code.google.com/p/reallysimplehistory/

Ajax and back button. Hash changes, but where is previous page state stored?

When using AJAX it's important to update the history manually using history.pushState

Then create a function testing for an onpopstate event and updating the content as required.

https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Manipulating_the_browser_history



Related Topics



Leave a reply



Submit