views:

2952

answers:

7

Is it possible to detect when the user clicks on the browser's back button?

I have an Ajax application and if I can detect when the user clicks on the back button I can display the appropriate data back

Any solution using PHP, JavaScript is preferable. Hell a solution in any language is fine, just need something that I can translate to PHP/JavaScript

+5  A: 

There are multiple ways of doing it, though some will only work in certain browsers. One that I know off the top of my head is to embed a tiny near-invisible iframe on the page. When the user hits the back button the iframe is navigated back which you can detect and then update your page. Here is another solution.

You might also want to go view source on something like gmail and see how they do it.

Here's a library for the sort of thing you're looking for by the way

George Mauer
Looks iframe maybe the way to go, thanks
Rushi
but iframe would mean another useless roundtrip...
vsync
+3  A: 

There's no way to tell when a user clicks the back button of presses the backspace key to go back in the browser, however there are other events that happen in a certain order which are detectable. This example javascript has a reasonably good method for detecting back commands:

The traditional way, however, is to track user movement through your site using cookies or referrer pages. When the user goes to page A, then page B, then appears at page A again (especially when there's no link on B to A) then you know they went back - A can detect this and redirect them or otherwise.

Adam Davis
+8  A: 

One of my favorite frameworks for doing this is Yahoo!'s Browser History Manager. You register events and it calls you back when the user returns Back to that state. And if you want to learn how it works, here's a fun blog entry about the decisions Yahoo! made when designing it.

Wayne Kao
Wow, you beat me to it, AND you gave a sweet link to a blog entry. Here, have an upvote!
Josh Hinman
+3  A: 

The Yahoo User Interface Library, my personal favorite client-side JS library, has an excellent Browser History Manager that does exactly what you're asking for.

Josh Hinman
A: 

Wow, all excellent answers. I'd like to use Yahoo but I already use Prototype and Scriptaculous libs and dont want to add more ajax libs. But it uses iFrames which gives me a good pointer to write my own code.

Now the other dilemna, Not sure which to select as "accept answer"

Also, how the hell do you comment on a answer? I see no link!

Rushi
Maybe you need to have a certain rep level before you can comment answers.
Matthew Schinckel
A: 

ah i seem to have gotten the "add comment" link, must be reputation thing

Rushi
+1  A: 

The dojo toolkit has functionality to deal with this in javascript. I don't think there is any good way to handle it in pure PHP.

Here is the docs page they have: http://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/back-button-undo

Scott S.