How to make back, forward and reload work in Ajax-based apps

Tags:

With Ajax apps getting more and more popular, there’s often the question of the browsers own controls working or not in the app in question. If you hit reload, you might end up back on the start page of the application, if you hit back.. who knows.

I think this is especially an issue in applications, where you would work with something, such as files, and you would go between views, like directories, where you might want to go back to the index, previous view or such.

There is a way to do this, at least in some browsers. It’s called location.hash

Applying the magic

As you might know, location.hash controls the #part in the url. For example in the following url, www.domain.com/hello#foobar, the location.hash part would be #foobar

It’s been known for a while that altering location.hash programmatically in JavaScript will make the browser record the change in the history. So if you were to change #foobar to #barfoo, hitting the back button wouldn’t go anywhere – only change #barfoo back to #foobar

See where this is going?

Basically, you’ll need to come up with some kind of a scheme for keeping track of the view the user sees: for example, you could always set the hash to the directory’s name the user is currently browsing. Then, you need some function for parsing the hash, and opening the correct view based on that.

There are no events for detecting when you press back or any of the other buttons, nor an event for seeing if the hash changed. But there is setInterval and the if-keyword. You can detect changes in the hash reasonably well by using setInterval with some function that checks if the hash was changed or not, which would then call your hash parser function.

Using this method, your application is reload, back and forward proof. It isn’t exactly very simple to do it, but I think it’s worth it to the user. I have implemented this approach in an Opera UserJS script that’s a file browser. You can check it out at the svn repo – just put it to your userjs directory and browse to some site with a directory listing, such as ibiblio.org/pub. I might port the script to “normal” JavaScript so that it can be used by going to some url, but for now it’s Opera only, so if you aren’t using it, you’ll need to download it to see the script in action.