tags:

views:

7299

answers:

5

Is there a way to respond to the back button being hit (or backspace being pressed) in javascript when only the location hash changes? That is to say when the browser is not communicating with the server or reloading the page.

+2  A: 

Google found this

http://www.hunlock.com/blogs/Mastering_The_Back_Button_With_Javascript

Sorry, misunderstood, is this what you mean

http://groups.google.com/group/jquery-en/browse_thread/thread/3826213cf78a92a9/355320d0b21552a4?lnk=raot&pli=1

The suggestion in the linked site is to add a click event on all links to check if the hash is being changed. They also suggest polling (as has been suggested by others here). Apparently IE8 has direct support for it.

Lou Franco
this article unfortunately focuses on window.onbeforeunload. Unfortunately this event is not triggered when only the hash in the location changes.
Steven Noble
+1  A: 

onLocationChange may also be useful. Not sure if this is a Mozilla-only thing though, appears that it might be.

pix0r
+6  A: 

I think you'll just have to use setInterval to poll the state of window.location.hash regularly.

var hash = location.hash;

setInterval(function()
{
    if (location.hash != hash)
    {
        alert("Changed from " + hash + " to " + location.hash);
        hash = location.hash;
    }
}, 100);

It's not instantaneous, but it feels responsive enough to me.

insin
I hate doing things like this...it seems horribly inefficient to have to poll things (check them over and over, ten times a second even). Before you know it, you have twenty of these types of intervals running and your CPU is bogged down doing nothing
davr
Nice to see that answers from StackOverflow are already hitting the top of google hits for old questions. This worked for me, but there were some conditions with problems in the code I was calling if it changed, which didn't let the hash change line execute. A good tip might be to do it last.
ironfroggy
+2  A: 

Did you took a look at this? http://developer.yahoo.com/yui/history/

powtac
this is really interesting. Now I need to figure out how it is doing this behavior
Steven Noble
ah, so this also works by polling
Steven Noble
A: 

I have created a solution which may be of use to some people. http://www.bajb.net/2010/02/browser-back-button-detection/. Simply include the code on your page, and you can write your own function that will be called when the back button is clicked.

I have tested in IE, FF, Chrome, and Safari, and are all working. The solution I have works based on iframes without the need for constant polling, in IE and FF, however, due to limitations in other browsers, the location hash is used in Safari.

Brooke