Browser Back Button Detection

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.brookebryan.com/code/backbutton/
or you can download the source from: http://www.brookebryan.com/code/backbutton/BackDetect.zip

72 Responses to “Browser Back Button Detection”

  1. Bill says:

    Great work Brooke. I would like to be able to use this to go a bit further. When someone has hit the Back button I present them with a confirm box warning them that any input data will be lost if they have not saved. If they click OK, the back button basically executes. If they click Cancel, they remain on the current page.

    Now, I’ve been able to get it so that if they click Cancel they stay on the page but if they click OK nothing happens OR no matter which button they click, the history.back executes.

    Any suggestions?

    Thanks.

  2. Andrew says:

    Hello everyone!
    Thanx, Brooke for good script!

    For those who want use “document.location” instead of stabdart back button behaviour, you can use setTimeout:

    function goSomewhere () {
    document.location.href = ‘http://somewhere.com';

    }
    bajb_backdetect.OnBack = function(){
    setTimeout(‘goSomewhere()’, 1);
    }

    Thanx.

  3. MaX says:

    Hi,
    I find out your elegant and precoius solution,
    but what about the ‘n’ times you click the back button?
    If I press the 2nd time the back button, the page go back…
    Thanks!!!

  4. Josh says:

    Hello,

    I was just wondering if its possible (using your style of javascript) to track the back button being clicked from the page before.

    So say I have a script on my page, then I navigate forward to a new page (with no script) then I navigate back.

    On the last back stage is it possible to be triggered or will it require a script on the page itself which back is being clicked?

    Thanks

  5. Kana says:

    Thanks a lot!

  6. SenTenceD says:

    excellent work! thanks for sharing :D

  7. Rajesh Kumar says:

    Hi Brooke. You are really awesome. Thanks for this great fix. I have struggling and searching the whole internet for a week and found your solution today. (rock)

  8. Ravi says:

    Your back button code is working fine but can you please send me the Algorithm for backbutton. Please let me know your feed back

  9. Melissa says:

    Hi Brooke,

    The first code I got working for this issue – BIG HOWEVER though – When I click the back button once, it pops up the alert and halts the “back”. But if they click the Back button again, no alert and the back proceeds.
    What can be done to handle multiple clicks of the back button?!

    Thanks! Need help asap – hope you’re still viewing this site.

    Melissa M

  10. afsheen says:

    Hi,

    I need code for redirecting to a specific page (instead of previous page) when the user clicks on browser back button using ajax(or ajax+jquery).

    Please help.

    Thanks in advance :)

  11. Mike says:

    Great script… thanks.

    I have an issue if the back button is pressed quickly i.e. before the page has rendered. I had thought about something like deleting the history but this is not possible on most browsers.

    Thanks

  12. Am says:

    Thanks. I am wondering if you had any thoughts of how this would be implemented this without iFrames support? Also how about using hashchange function instead of a time sensitive counter? example –

    $(function(){

    // Bind the event.
    $(window).hashchange( function(){
    // Alerts every time the hash changes!
    alert( location.hash );
    })

    // Trigger the event (useful on page load).
    $(window).hashchange();

    });

  13. Brooke Bryan says:

    The main reason for not using the hash is just to have less visible impact for customers. There is however a watch setup for the hash in Safari/Chrome as the iframe hack isnt supported.

    The code provided also does not use jQuery, which would make things easier, but there is no need to include all of jQuery when its not needed

  14. Brooke Bryan says:

    You can just change the OnBack function to stop the history.back() from being called. or, by just taking history.back() out of the code completely.

  15. Brooke Bryan says:

    with the OnBack function, you could just check the output of a js confirm(), and then push the history.back() within there.

  16. Am says:

    Agreed on your thought of not using jQuery when not needed. I am developing something for the mobile and hence all are WebKit based browsers (iPhone & Android). The timer thing makes me nervous and this page can go in the background for ages. Hence I was looking for a way to not use the timer based way. Do you know if there is a method which works on Safari without the timer? It can use jquery too if it helps since I use it anyways for some other things we are doing.

  17. Rajveer singh says:

    awesome work Brooke….very nice…best of luck for future…:)

  18. fabioem says:

    Fantastic!!!!

  19. MMeah says:

    This is great work that you did. Mad props. Works on my Android 2.2 Galaxy S.

    May I get permission to use this in a jQuery Mobile project I am working on? I need to detect if the user clicked on the back arrow on an iOS or Android device.

  20. Sanjeev says:

    Great help Brooke, But i need something like
    If i press back button than one alert will appear that will ask ‘Yes’ or ‘No’. When i select ‘No’ than i want to stay on same page otherwise i will be logout or on login page. So could you just help me out on this.

    Thanks,
    Sanjeev

  21. Brooke Bryan says:

    You could use onbeforeunload and return the string, however it will only give you ok and cancel I believe (text changes per browser), so you get the functionality, but limited customization


Leave a Reply