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. Robert says:

    Excellent work, this is just what I was looking for. I noticed the code has the whitespace removed, do you have another copy available so I can read it easier? I wanted to make sure you didn’t implement the polling for safari, though after reading your post again it doesn’t sound like you did. Safari will not be used In the application I will apply this to.

  2. Brooke Bryan says:

    The un-minified code can be found by removing the .min from the JS location when viewing the demo: http://www.brookebryan.com/code/backbutton/backfix.js

  3. Geoge says:

    It ‘s awesome.
    But I used it to detect back button acion and at that moment I wanna submit a form and redirect the new page spesified by server response.The server get the request,but the browser always go back the old page in the history and ignore the server response.
    So ,it can detect back button acion but can not stop the go back action,doesn’t?

  4. Brooke Bryan says:

    The script will not force the browser to go back to the page in history unless you specify

    bajb_backdetect.OnBack = function()
    {
    history.back();
    }

    Hope that helps.

  5. Marc says:

    It looks like this is the best script available, but it does not work in Firefox 3.6.8 for me.

    The function to fire the alert is never fired.

    What can it be?

    Thanks in advance!

  6. Brooke Bryan says:

    Have you tested this on the demo? http://www.brookebryan.com/code/backbutton/

    I am using Firefox 3.6.8 and am not having any issues.

    Alternatively, pop over to http://www.supportbuddi.com and mail me your Support Code.

  7. Charles says:

    Hi Brooke,

    Do you have some thing to fix forward button ?

    I used your backfix.min.js in JSF/Facelet xhtml to call a non-display button, that button calls a backbean method when user clicked backup button, works great, but need to fix forward button also.

    If possible, can you publish the code in backfix.min.js ?

  8. Dan says:

    Wonderful! We needed a way to make the back button work because of a major page transition with jquery effects causing them to think it was a new page they went to and so if they wanted to go back to the original screen with the back button, they couldn’t. We are sending an email with a link to the page, so no history will be in place when they go to the page. Your implementation worked like a charm. THANK YOU!

  9. S K says:

    Thanks!

    The script seems to work well in IE but unfortunately not in Firefox or Safari.

    Is this a known issue?

    Regards,

    Stefan

  10. andrew says:

    Does this work only for single browser-back ? What if I press back several times?

  11. Another Dan says:

    So I’m trying to mod your code (keeping your author stamp) so that this function redirects someone to a particular page when they click the back button. I’m using ASP.NET Ajax to create a Search page that asynchronously populates a gridview with the search results. Users then click an item that they were searching for, and get to the proper info page. But when they hit back, their search results disappear. I tried using Session items to store the information that is loaded into the gridview when they go to the page, but all of that code is Server code, and the back button bypasses all Server code and executes client-side only. So I thought that if I could get this code to fully redirect users to the search page again, their results would appear as though there were no issues. But I’m having an issue getting the code to execute anything other than throwing up Alert boxes…

  12. Brooke Bryan says:

    Can you provide the code you are using inside the function “bajb_backdetect.OnBack = function()” You should just be able to do window.location = ”;

  13. Brooke Bryan says:

    The script was fully tested in IE, Safari & Firefox. and didnt have any bugs. Were these tests done on my demo page, or on your own install?

  14. Brooke Bryan says:

    You would need to place the code on the pages you are going back to, but yes, you could have it working several times.

  15. Brooke Bryan says:

    You can find the unminified code at http://www.brookebryan.com/code/backbutton/backfix.js

    As for the forward button, I haven’t yet tackled that problem.

  16. Another Dan says:

    I got it to work. I was modifying the base code on the JS file to do this:

    OnBack: function() {
    document.location = ‘default.aspx?itworked=1′;
    }

    but later in the code, it executes a history.back() that I had to mod in order for the redirect to land me where I wanted to go:

    BAJBFrame: function() {
    var BAJBOnBack = document.getElementById(‘BAJBOnBack’);
    if (bajb_backdetect.FrameLoaded > 1) {
    if (bajb_backdetect.FrameLoaded == 2) {
    bajb_backdetect.OnBack();
    //the history.back() function needs to be removed or ignored
    //add your custom location afterwards

    //history.back();
    document.location = ‘search.aspx’;
    }
    }
    bajb_backdetect.FrameLoaded++;
    if (bajb_backdetect.FrameLoaded == 1) {
    if (bajb_backdetect.Browser.IE) {
    bajb_backdetect.SetupFrames();
    }
    else {
    bajb_backdetect.FrameTimeout = setTimeout(“bajb_backdetect.SetupFrames();”, 700);
    }
    }
    }

  17. Another Dan says:

    Very excellent stuff though! I have been looking forever to find a way to hijack the back button! I very much so appreciate this segment!

  18. Hector says:

    Great script!!!! I’ve been trying to get this with little luck at times. Your script works really well.

    There are times when it doesn’t work on a dynamic generated page generated by the server after a POST. Anyway is still a great script, congratulations and thanks for posting this. I have no problems with what I mention but decided to tell you if such info is useful for you.

    Details:
    Firefox 3.6.10
    I generate the first page via Perl with your script on it.
    Page kinda “flicker” on the back button and then voilá, your script is active.
    Then I make the POST
    Another dynamic page is generated with the same implementation but this one won’t work. I don’t know why. Perhaps a mousemove will do the trick for me.

    Thanks, good luck.

  19. Hector says:

    Bryan, please pay no attention to my previous message (except on the congrats!) I got curious and began to play with it, I have some settings and functions that affected the script, it works just fine as expected. Thanks, congrats again.

  20. rachana says:

    Excellent . Thanks for your wonderful script.
    Good work guys .

  21. Hema says:

    Hi bryan,

    Excellent work….

    It helped me a lot…. :)

    But the same script does’nt seem to work with firefox 3.0.5 :(

    Any help would be greatly appreciated…

  22. Diego says:

    Great code! It’s possible to detect if the page that the browser load is called by BackButton instead of normal navigation?

  23. Sandy says:

    Bryan,

    This is what I was looking for. And it works great.
    Apart from this, we are even trying to see if we can override/disable the IE “Recent Pages” link just beside the Back/Forward Buttons.
    I know that what I am asking for is overriding the browser functionality… but any suggestions would be really appreciated.

    TIA,
    Sandy

  24. shishir says:

    The code does not work in Chrome browser. Can you help me out?

  25. Carsten says:

    Nice!

    If anyone does not get it to work in Firefox: the script apparently needs blank.html so don’t delete that file (like I did in the first place, to discover it wasn’t working there).

    This could be a nice jquery plugin, Brooke!

    Kind regards,

    Carsten

  26. sid says:

    not working for desktop chrome. on android chrome, it detects it to be safari. any intention to release a fix for chrome?

  27. Brooke Bryan says:

    Chrome has now been fixed

  28. Vetle says:

    Hi,

    Useful stuff! :)

    However, there is no mention of any license in the JavaScript file, so I’m a bit worried about including it in my current project. Could you possible add a license or is it available to use freely?

  29. Brooke Bryan says:

    Feel free to use it where you like.

  30. Kelly Wu says:

    After replacing “history.back” with URL redirect in your script, it can redirect user to the desired page after back button is clicked. However, it will go back to old page if I click back button continue clicking back button very fast.
    Any suggestions would be greatly appreciated.

    Best Regards,

    Kelly

    P.S. this is my seconds post. I don’t know why my first post was removed. Did I do something wrong?

  31. Sneha says:

    Hi Bryan,

    The script is awesome!!! and you have done a gr8 job.

    Its working fine for Firefox,IE 8 :)
    I have also tested on Chrome,but its not working for me :(
    I have used the latest version after your fix.

    Please tell me where i went wrong.

  32. James says:

    Hello, I’m trying to understand your intriguing code. How does the “bajb_backdetect.FrameLoaded” variable end up with the value of “2″ ? -James

  33. Denesh says:

    hello Bryan,is this code depends on time ??.
    On back i changed your function to redirect another page in js it works good when page loads fast and clicked but same code doesnot work when page loads taking time and goes back instead of redirect.Can u please suggest me for proper solution

  34. Greg says:

    Brooke,

    I am using your backfix, and it shows my custom alert without problems. However, it always goes back for me after displaying the alert. Based on your replies, it looks like after displaying the alert the browser is not supposed to go back unless history.back() is invoked in the OnBack function override. In my case I just display my alert in the override, just like in your override example. I am using IE 6.0. Thank you.

  35. wally says:

    Hi,
    I downloaded just yesterday your script, I think it is VERY GREAT, but it still does not works with chrome (v.10.0.648.133). The chrome fix is an additional script or it has been integrated in the backfix.min.js?
    But my bigger issue is another one! I have a page with two iFrames. I linked your script in the header of the parent page, but it does not detect the back button. The OnBack event fires only when I leave from the parent page, but I need to use it within the frames navigation.
    Can U help me please?

  36. nikhil says:

    how prevent user from redirecting to back page

  37. symcbean says:

    Thank you BB for a well implemented code for an elegant solution.

    The only thing wrong with it is the amount of time I spent trying to fid your solution :)

    I imagine that a lot of people looking for a solution to this problem will be in a similar boat to myself – needing to control state browser side – and unable to cater for all eventualities serverside. The 2 major parts of this are controlling the back button – but also solving the new window problem (if only HTML5 had included an API for enumerating windows/tabs!).

    For the benefit of those still trying to solve the new window/tab problem – for every browser I’ve used, a new window has no history (but they differ in where the count starts – some start at 0, some at 1). And you don’t need special privileges to read history.length

    (note that this might sound like another way to detect the back button – for numerous reasons, it’s not)

    HTH

  38. Brooke Bryan says:

    Hey, yes the script is dependent on time. This is due to the limitations with some browsers, as they do not store the history of frames unless they are loaded a while after the original page has loaded.

  39. Brooke Bryan says:

    Can you provide any examples of the page?

  40. Brooke Bryan says:

    Sorry, I have not tested this in IE6. You should probably update your browser, its far too old for the modern world.

  41. Delphiboy says:

    May seem stupid, but if you change the line with “history.back();” in the JS file with “document.location=document.location;”, it will prevents the user from going back and you don’t hardcode the page name!

  42. Brooke Bryan says:

    Yes, you can do that, however, the script is only to detect the click. The action you take once detected is totally your own choice :)

  43. Phil says:

    this unfortunately does not work in chrome..

    it accurately displays the alert window, but then goes back to the previous page in the browse’rs history

  44. adi says:

    Hi,
    Thanks for that. It is very useful script.
    I do have problem though:
    I commented out the history.back() lines in your code, so browser will not go back after running the onBack function ( I suppose this is what I needed to do since using the script as it is showed the alert and then went back… ). This work fine but only for the first click on the back button. Second click ( waiting 20 seconds between clicks ) will not be intercepted.
    Can you advise on that ?

    Thanks
    Adi

  45. adi says:

    p.s. that was tried on ie8.
    in ff it seems the script worked fine out of the box ( no need to comment the history.back() )

  46. Mi says:

    Hey,

    Thank you so much for this script it saved my life!
    It works fine in Chrome, IE and Opera.
    Although it doesn’t work in Firefox 4! :( I have to click several times to go back, and it goes back to the main page, not to the previously as supposed. Can you please help me?

    Once again, thank you :)

    (sorry for my bad english)

  47. Mi says:

    Hi once again :)

    I’ve noticed that in Firefox actualy it works, but only if i wait a few time… How can this happen?

    Thanks!

  48. Quang says:

    Hi guys,

    I’ve try your suggest above ! that’s great ! but I have some problem like :

    I have a survey system the work flow of this is
    1 List survey available for you to do.
    2 Read survey
    3 Thanks you for doing survey (there is a button to return list survey)

    using your code I am able to prevent user back to Read survey but when they do some cheating
    they click on button to return list survey and now they click back to return thanks and then Read survey
    My website was crashed.

    Hope you guy have some solution to help me

  49. Ravi K N says:

    Hi Bryan,

    It works great when the page loads fast. However how to handle the situation when the page takes lot of time to load?, In My case, it is calling the back function as the page is taking lot of time to load.

    Please suggest.

    -Ravi

  50. Rakesh says:

    Hi,
    I have a same kind of requirement like,if we click back button i need to go back to index.jsp/login.jsp.

    I have downloaded the source code from the site,which was working,but it was not working in my application,I tried to rename the downloaded files of zip folder.it is not working,Can any body help

    Thanks in advance..

    Rakesh k


Leave a Reply