Browser Back Button Detection 97

Update: (27th Jan 2011)  A fix for Chrome has now been uploaded.

Ever since the web moved into the 2.0 generation, websites are increasingly using ajax to build up content, and navigate around without reloading the entire page. There is one major problem with this, and that is the browser. Until now, browsers to not trigger events for when the user is flipping between pages using the navigation buttons. This has been a problem with flash sites for a much longer period of time, with the user clicking back in the browser expecting to see the previous page shown in flash, but instead, they are taken to the last site they were on.

When improving the functionality of our Automated Chat Software, Intellichat, we had many requests from customers asking for the chat window to not launch when the user clicked back in their browser. After a lot of research into the problem, and how to detect it, I found the solution to be based around iFrames (as much as I hate them). When the user clicks back on their browser, they will initially navigate back through the iframes on the page before main page can go back.

This solution works great in Firefox and IE, however Safari needs an alternative solution. This is based around location hash tags (I find this solution quite messy, and easy to spot from the users point of view). When the page first loads, you can set the window.location.hash to anything you want, and then simply check the window.location.hash variable every few milliseconds to see if it has changed. Once it changes back to an empty value, you can see the user clicked back.

The Solution
I have made a very reusable javascript class, that can be simply dropped into your web page, and when the user clicks back, it will call a function. The default function on this call is a javascript alert “Back Button Clicked”.

To replace this functionality, you simply need to override the OnBack function. This can be done by using the code below.

<script type="text/javascript">
bajb_backdetect.OnBack = function()
{
alert('You clicked it!');
}
</script>

This will now replace the “Back Button Clicked” alert with a “You clicked it!’” alert.

You can see the code in action at http://www.bajb.net/code/backbutton/
or you can download the source from: http://www.bajb.net/code/backbutton/BackDetect.zip

Share/Bookmark