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
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.
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.
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!!!
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
Thanks a lot!
excellent work! thanks for sharing
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)
Your back button code is working fine but can you please send me the Algorithm for backbutton. Please let me know your feed back
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
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
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
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();
});
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
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.
with the OnBack function, you could just check the output of a js confirm(), and then push the history.back() within there.
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.
Maybe this thread would be helpful for you: http://stackoverflow.com/questions/680785/on-window-location-hash-change
awesome work Brooke….very nice…best of luck for future…:)
Fantastic!!!!
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.
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
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
thank you for this jquery it was really very use full to me as i was tried for this long time thank you
Thanks for the code snippet.. extremely useful. Really good job!!
awesome work Brooke….very nice…
Hi Brooke,
i used following code
function goSomewhere () {
document.location.href = ‘thank-you’;
}
bajb_backdetect.OnBack = function(){
setTimeout(‘goSomewhere()’, 1);
}
But not work it not restrict back browser link.
my issue is that on my project thank-you page page come from after payment success but if click on back on browser the link go to payment page and payment mode fire and payment complete. i mean payment is done by two time.
can u please suggest me what i change on that code.
Hi Brooke,
Thanks for sharing this, this is really helpful. But I am facing one issue in this.
This code works fine in IE but in Firefox and Chrome it didn’t work. The alert is coming up in all browsers. Actually, I am calling server side event with the help of CallBack event. This works fine in IE but in firefox and chrome the server side event is not getting fired. The same server event is getting called from other location and it works fine in Firefox and chrome as well. Below is the sample code:
function ReceiveServerData(rValue)
{
//fetch the callback return value;
}
bajb_backdetect.OnBack = function () {
// alert(“back button clicked!!”);
CallServer(‘back:@:’, “”);
}
//Default.aspx.cs
//The below code is registered in Page load event.
String cbReference = Page.ClientScript.GetCallbackEventReference(this, “arg”, “ReceiveServerData”, “context”);
String callbackScript;
callbackScript = “function CallServer(arg, context)” +
“{ ” + cbReference + “;}”;
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), “CallServer”, callbackScript, true);
public void RaiseCallbackEvent(String eventArgument)
{
// Do something
}
public String GetCallbackResult()
{
//return callback result
}
The same CallServer() method is getting called from other location and its working fine in firefox and chrome as well.
Can you help in this?
Thanks,
Brijen Patel
Unbelivalble!!!
Thanks~
Hi! Excellent code.
I would like to ask if the issue on “clicking the back button more than once” has been resolved?
Script does not wok on succeeding clicks of the back button.
Thanks a lot!
Cool feature ! What is the license for this code ?
Great man, done very well
It adds #b to the current page url on chrome. How to avoid that ?
Thanks for the script but on mobile device browsers it is not a success. After clicking 2-3 fast clicks user route back to old page.
Any solution for this?
Thanks a lot for this masterpiece
You are free to use the code wherever you like
Due to the way it detects for the back button, the hash location is required to be set. You could edit the code to have something other than #b, but with this method, that is required in Safari & Chrome
I haven’t looked into a solution for this, as it could cause frustration to the end user. It would probably be possible with a few tweaks though
About after 2 weeks search found your solution. Good job and thank you very much.
Hi,
I am trying to redirect it to my custom page.
$(function(){bajb_backdetect.OnBack = function()
{
setTimeout(function(){window.location.href = /Message.aspx?MESSAGEID=GenericExceptionCode’;}, 10);
}});
It doesnot work when I am using backbutton hit more than once in a quick succession. Am I doing something wrong?
Also I am not seeing it working properly in Mozzila. The back event gets detected though but even after execution of window.location.href it goes back to previos page. Please help.
Thank you sincerely for your code! its increible.
I have used it to avoid open a window on beforeonunload when user click in navigator back button.
I have tested it in IE, Firefox,and Chrome, and in Firefox and Chrome works correctly.
In IE (7, 8, 9) works, but there is a “but”, I have to clicked twice in order to back to the previous page.
Do you know why?
Thank you so much!
What is the license for this code ?
You can use this under http://cubex.io/licence
I cant’s find the source code to download. Could you please help me with the link.
Thanks.
Links updated. Sorry about that
Hey
Brooke
Thanks you so much for your solution, Back Button Detection it’s great! and you are amazing
Thanks Man
Thanks a lot