102

How to disable browser's BACK Button (across browsers)?

priyanka.sarkar
  • 25,766
  • 43
  • 127
  • 173
  • 94
    You don't own your users' computers or their browsers. – Instance Hunter Jun 07 '09 at 04:58
  • 47
    +1 Because although I agree that disabling the browsers back button is 'bad practice', I see no reason for downvoting the question itself, answering and explaining why is the way to go imo. – ChristopheD Jun 07 '09 at 05:14
  • 45
    Why are we being hostile to this question? For all we know, the person asking this question already knows that this is poor usability practice but are just following requirements, or maybe they just want to learn something. Why don't we just pretend this is a hypothetical question, and answer how we would do it IF we were to do that sort of thing? – thomasrutter Jun 07 '09 at 05:22
  • 5
    Some things should never be done, regardless of any desire to do them. Having a non-negotiable requirement for this instantly says that the requirements were set by people with no business setting them, which is a much bigger problem. – annakata Jun 08 '09 at 09:10
  • See: http://stackoverflow.com/questions/87422/disabling-back-button-on-the-browser – Shog9 Nov 04 '09 at 19:50
  • 38
    ugh, I authored the most awesome comment ever, but lost it when I accidentally hit the back button. – Dan Williams Jul 28 '10 at 20:11
  • 4
    This is like asking: How to disable reverse gear with a traffic sign? Sure, you can put up a one-way street sign, but you can never actually prevent people from going the wrong way. Traffic designers know this and build some tolerance for this into the system when they can. Web application designers (should) do the same thing. – reinierpost Jun 14 '11 at 12:05
  • The only back that should be done here is to the drawing board. – Jagd Jan 16 '12 at 21:24
  • 2
    how do we create web games that don't aggravate our customers when they accidentally bump mouse4 with their thumb? maybe disabling 'history.back' isn't the right approach, what we really need is access to mouse4/mouse5 events (and a sensible preventDefault() model that incidentally disables any back/forward default behaviors) - as far as i can tell this isn't possible (which is probably why a million people are looking to disable history.back) – Shaun Wilson Sep 15 '14 at 08:42
  • @reinierpost a better analogy would be to want to stop the car rolling back on hills by removing all ability to reverse the car, the original idea is a good one but the wrong solution has been suggested, if you think why they are asking its probably because the cached data would corrupt the system if submitted again so they probably really want to expire the page – MikeT Jan 04 '17 at 16:36
  • @MikeT: So design the system to keep resubmitted cached data from corrupting it. – reinierpost Jan 09 '17 at 10:58
  • @reinierpost my point was they have a valid problem, and what seems to them to be a solution, in reality the solution is awful but they don't know that. we need to tell them why and then suggest the correct solution. your analogy of using traffic signs to directly control the vehicle completely dismisses the entire problem as nonsensical – MikeT Jan 09 '17 at 11:59
  • @MikeT: good point, it's only nonsensical to someone who is aware of how the web works and who doesn't like tackling problems at the wrong end – reinierpost Jan 09 '17 at 15:07
  • If someone is programming a web-accessible workflow application for employees or users, it's completely legitimate to control browser behavior while they are in that workflow application. We're not talking about permanently destroying the capability in their browsers, we're talking about disabling it when it's being used specifically in the OP's application. Why go through some elaborate process when something as simple as having that specific page disable the back button is possible? – PoloHoleSet Jul 20 '18 at 15:27
  • @InstanceHunter - Actually, for a work application running on a secure network using company-owned equipment..... yes, we actually do own the user's computers and their browsers. – PoloHoleSet Jul 09 '19 at 20:29

20 Answers20

61

Do not disable expected browser behaviour.

Make your pages handle the possibility of users going back a page or two; don't try to cripple their software.

Toby Allen
  • 10,997
  • 11
  • 73
  • 124
Jonathan Fingland
  • 56,385
  • 11
  • 85
  • 79
  • 7
    Thanks dude, the thing is that if you're building an AJAX app, the cost-benefit tradeoff between disabling the back button, or going through your app and working out the appropriate back action for each and every possible scenario, may tend towards disabling the back button being the more attractive option of the two. – david.barkhuizen Dec 27 '12 at 15:36
  • I would agree with Jonathan, especially with the flood of redirect malware adverts that are currently flooding the internet, they already abuse the alert system to make leaving their pages difficult without giving them the ability to actually lock you on to their page – MikeT Jan 04 '17 at 17:02
  • "Disabling" back button is a very common use case: for any application requiring authentication/security you don't want a user to be able to press the back button and view pages that were seen by another user that was logged in. You'll see this behavior in any web application that requires log in, for example ameritrade.com. Unfortuantely, stackoverflow.com is not ironclad in this. If you log out and start hitting the back button, the first couple of pages in the log out seem to be protected, but you will be able to view content accessed by the logged on user :( – John Jul 20 '21 at 16:53
47

I came up with a little hack that disables the back button using JavaScript. I checked it on chrome 10, firefox 3.6 and IE9:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<title>Untitled Page</title>
<script type = "text/javascript" >
function changeHashOnLoad() {
     window.location.href += "#";
     setTimeout("changeHashAgain()", "50"); 
}

function changeHashAgain() {
  window.location.href += "1";
}

var storedHash = window.location.hash;
window.setInterval(function () {
    if (window.location.hash != storedHash) {
         window.location.hash = storedHash;
    }
}, 50);


</script>
</head>
<body onload="changeHashOnLoad(); ">
Try to hit the back button!
</body>
</html>

What is it doing?

From Comments:

This script leverages the fact that browsers consider whatever comes after the "#" sign in the URL as part of the browsing history. What it does is this: When the page loads, "#1" is added to the URL. After 50ms the "1" is removed. When the user clicks "back", the browser changes the URL back to what it was before the "1" was removed, BUT - it's the same web page, so the browser doesn't need to reload the page. – Yossi Shasho

Toby Allen
  • 10,997
  • 11
  • 73
  • 124
Yossi Shasho
  • 3,632
  • 31
  • 47
  • 1
    It looks like this script adds "#" to the URL when the page loads, and every 50ms, it appends a 1 to the URL. – ashes999 Sep 06 '11 at 14:13
  • 7
    This script leverages the fact that browsers consider whatever comes after the "#" sign in the URL as part of the browsing history. What it does is this: When the page loads, "#1" is added to the URL. After 50ms the "1" is removed. When the user clicks "back", the browser changes the URL back to what it was before the "1" was removed, BUT - it's the same web page, so the browser doesn't need to reload the page. – Yossi Shasho Nov 29 '11 at 12:35
  • 1
    note that the URL changes twice: We only do this in order to disguise the implementation, so nobody will see that we added "1". So actually when the user clicks back, the page re-adds the "#1" for a moment and removes it again. BTW - it doesn't have to be "1", it can be any string. – Yossi Shasho Nov 29 '11 at 12:35
  • 2
    The problem with this is that the page is scrolling to the top every 50 ms. If you have a form larger than window height, this will make it impossible to fill inn the form values. – 3komma14 Oct 17 '12 at 09:59
  • Thanks very much. This is super useful for a JavaScript based particularly interactive page I have, where scrolling left and right is part of the mechanic. This helps eliminate the problem of the scroll gesture on Mac OS X taking users "back" a page by accident (all to easy to do if they are already scrolled all the way). – Iain Collins Oct 28 '12 at 02:05
  • @3komma14 The page only scrolls to top if the user clicked back. – Yossi Shasho Aug 11 '13 at 12:16
  • will adding this script, reduce the SEO? as we are changing url, so it might affect the SEO. – JVJplus Aug 06 '21 at 05:54
  • It only changes the hash part of the URL, so I don't believe this should affect the SEO – Yossi Shasho Aug 27 '21 at 09:36
34

Others have taken the approach to say "don't do this" but that doesn't really answer the poster's question. Let's just assume that everyone knows this is a bad idea, but we are curious about how it's done anyway...

You cannot disable the back button on a user's browser, but you can make it so that your application breaks (displays an error message, requiring the user to start over) if the user goes back.

One approach I have seen for doing this is to pass a token on every URL within the application, and within every form. The token is regenerated on every page, and once the user loads a new page any tokens from previous pages are invalidated.

When the user loads a page, the page will only show if the correct token (which was given to all links/forms on the previous page) was passed to it.

The online banking application my bank provides is like this. If you use the back button at all, no more links will work and no more page reloads can be made - instead you see a notice telling you that you cannot go back, and you have to start over.

thomasrutter
  • 114,488
  • 30
  • 148
  • 167
  • 1
    My bank takes a different approach - it terminates the session entirely. Using the back button is equivalent to loging out. – RobG Mar 16 '12 at 07:43
  • That sounds like the same approach. They're detecting that you've gone back and thrown up an error condition. – thomasrutter Nov 26 '12 at 00:20
  • also joomla work around the token solution, a token is generated by every page and every form, infact there are some issues about this practice, like "when a user stay too much on a page and his token expire" – Matteo Bononi 'peorthyr' Jun 18 '13 at 12:00
  • 1
    Don't get me wrong, there are LOTS of issues with this practice. I'm not recommending it, I'm just saying how it's normally achieved. They pass unique tokens between pages in order to detect that you haven't followed one of the expected links from the previous page, and then terminate the session or show an error. It breaks the back button, it breaks tabbed browsing, it breaks bookmarking and/or sharing links, and more - and what's more, it doesn't really solve any problems. – thomasrutter Mar 21 '14 at 02:53
  • if the problem is that information is lost or breaks already if the user tries using the back button, then disabling the back button would be a more desired approach. – PoloHoleSet Jul 20 '18 at 15:31
  • There is no scenario in which losing information or breaking your application when using the back button can't have been fixed by building the application correctly. – thomasrutter Jul 23 '18 at 00:11
27

This question is very similar to this one...

You need to force the cache to expire for this to work. Place the following code on your page code behind.

Page.Response.Cache.SetCacheability(HttpCacheability.NoCache)
Community
  • 1
  • 1
RSolberg
  • 26,821
  • 23
  • 116
  • 160
  • 15
    Note that making the page un-cacheable does not achieve what the OP wanted: to disable visiting pages using the back button. Even if a browser obeys no-cache when using the back button (which browsers are not obliged to do AFAIK) they still provide a way to reload that page (usually after showing a warning dialog). So if you really don't want your users going back to that page, this may be worse, since the request for that page will HAVE to make its way all the way to the origin server. You will need something server-side to detect that the page has been revisited. Headers can be ignored. – thomasrutter Nov 11 '09 at 03:31
  • Disabling back button is a very common use case: for any application requiring authentication/security you don't want a user to be able to press the back button and view pages that were seen by another user that was logged in. You'll see this behavior in any web application that requires log in, for example ameritrade.com. Unfortuantely, stackoverflow.com is not ironclad in this. If you log out and start hitting the back button, the first couple of pages in the log out seem to be protected, but you will be able to view content accessed by the logged on user :( – John Jul 20 '21 at 16:52
10

While i'm looking for the answer myself, "Best Practice" is.... outdated... Just like browsers are.(Really browsers are ugly fossils)

The best/safest solution would be for browsers to implement a method/request where the user can grant the page the ability to control the interface.

Why? Because for my current project i'm building a 100% JavaScript built and controlled interface.. And back button's have no place in my project since there is no page change. (Ie bloody fast and no page-flashes because of a refresh.. Just like a real application!)

I know why the ability to "highjack" the interface isn't there, and i understand it. But atleast we should have the ability to request it from the browser! Now that would truly be "best practice" without the highjack dangers.

But browsers being browsers.. I don't expect anything exiting to happen in this regard.

StellarDevil
  • 101
  • 1
  • 2
  • 1
    100% disagree, while this functionality would be wonderful for 99% of web developers, that leaves the remaining 1% that would abuse this functionality, it is way too dangerous to allow a website to control your ability to use the internet, in my opinion cross domain redirect script either need banning or allowing the to confirm if the script is allowed to run because of just this sort of abuse – MikeT Jan 04 '17 at 17:12
  • @MikeT - How would disabling a "back" button while navigating on my own specific application pages inhibit anyone's ability to use the Internet? – PoloHoleSet Jul 09 '19 at 20:34
  • @PoloHoleSet if you have the ability to disable the browsers back button then so does everyone, all you need is one redirect to send you to a page you didn't want to go to and if they can disable your navigation controls in the browser how do you escape? I'm sure you have come across the "you have a virus page" where they prompt you to install their virus to remove the non existent virus now imagine that site where they can actually prevent you from leaving – MikeT Jul 16 '19 at 09:21
  • @MikeT - I can enter any other url in the navigation window, I can close a tab, I can disable javascript. The point isn't whether someone CAN, because you can, I can, anyone can. As a matter of policy, people are saying that you SHOULDN'T, if you can. We're not talking about how we'd design a browser, we're talking about how we program an application. – PoloHoleSet Jul 16 '19 at 13:58
  • @PoloHoleSet if you are going to lock the navigation you would need to lock out more than just the back button, as browser history and typed urls would also provide users a way to bypass your work flow. and like i said we aren't talking about what you or i would do but the malicious element, if the only way to prevent a malicious website taking control of your browser is to disable all js on your browser then you have broken the internet as the modern web relies on scripts to provide content which is my point, if you want that much control over your users create a app to serve your workflow – MikeT Jul 16 '19 at 16:15
  • @MikeT - No, because clicking the back button is an ingrained habit. If there is a hard stop when they click the back button and they want to go back, they will use the "back" navigation buttons in the application, or they will realize they can't go back. Again, I'm talking about internal workflow apps for professional employee users. I AM talking about what you or I would do, because that's the question at hand. You seem to think we're talking about some kind of fundamental crack of how the browser works. I've seen several solutions that disable the function via code. – PoloHoleSet Jul 16 '19 at 21:16
  • @MikeT - There's nothing about the programming I'm talking about that would make a browser somehow more vulnerable to malicious attack, so I'm really not sure what it is you are going on about. No one is talking about altering the core browser code. If I disable a browser, programmatically, and they go to another site, their browser operates like it normally does. If I have to disable my JavaScript, then, no, I haven't broken the Internet as I would be doing it if I wound up cornered on a malicious site I had not intended to go to. I would turn it back on once free. – PoloHoleSet Jul 16 '19 at 21:21
  • What I do on my site has zero impact on how users would use their browsers on other sites. Your claims otherwise don't seem to be based on anything substantial or real. – PoloHoleSet Jul 16 '19 at 21:21
4

I was searching for the same question and I found following code on a site. Thought to share it here:

function noBack()
{
   window.history.forward()
}
noBack();
window.onload = noBack;
window.onpageshow = function(evt){ if(evt.persisted) noBack(); }
window.onunload = function(){ void(0); }

However as noted by above users, this is never a good practice and should be avoided for all reasons.

user35443
  • 6,309
  • 12
  • 52
  • 75
user704988
  • 436
  • 1
  • 9
  • 24
  • 2
    it would be good if you could state the reasons why it should be avoided. – Chris Snow Nov 18 '12 at 08:13
  • As per my understanding, you technically cannot disable the Back button on someone's browser, you can only make it so that the button isn't available or continues to load the same page. Rather than doing it thru JS, use server side code and use proper logic which doesn't need to use Back button. Alternate action like reloading the same page or showing custom message should be used. – user704988 Nov 20 '12 at 01:22
2

I also had the same problem, use this Java script function on head tag or in , its 100% working fine, would not let you go back.

 <script type = "text/javascript" >
      function preventBack(){window.history.forward();}
        setTimeout("preventBack()", 0);
        window.onunload=function(){null};
    </script>
Abdul Khaliq
  • 2,139
  • 4
  • 27
  • 31
2
<body onLoad="if(history.length>0)history.go(+1)">
London
  • 21
  • 1
2

There have been a few different implementations. There is a flash solution and some iframe/frame solutions for IE. Check out this

http://www.contentwithstyle.co.uk/content/fixing-the-back-button-and-enabling-bookmarking-for-ajax-apps

BTW: There are plenty of valid reasons to disable (or at least prevent 1 step) a back button -- look at gmail as an example which implements the hash solution discussed in the above article.

Google "how ajax broke the back button" and you'll find plenty of articles on user testing and the validity of disabling the back button.

DallinDyer
  • 1,378
  • 13
  • 14
  • Check out Facebook's new photo viewer as well. Notice that the back button takes you back a photo (which is what you want) instead of doing the browser default – DallinDyer Mar 04 '11 at 16:24
2

If you rely on client-side technology, it can be circumvented. Javascript may be disabled, for example. Or user might execute a JS script to work around your restrictions.

My guess is you can only do this by server-side tracking of the user session, and redirecting (as in Server.Transfer, not Response.Redirect) the user/browser to the required page.

devio
  • 36,858
  • 7
  • 80
  • 143
1

Try this code. Worked for me. It basically changes the hash as soon as the page loads which changes recent history page by adding "1" on URL. So when you hit back button, it redirects to same page everytime.

 <script type="text/javascript">
    var storedHash = window.location.hash;
    function changeHashOnLoad() { window.location.hash = "1";}
    window.onhashchange = function () {
        window.location.hash = storedHash;
    }
</script>

<body onload="changeHashOnLoad(); ">

</bod>
Psth
  • 250
  • 1
  • 2
  • 11
0

Globally, disabling the back button is indeed bad practice. But, in certain situations, the back button functionality doesn't make sense.

Here's one way to prevent unwanted navigation between pages:

Top page (file top.php):

<?php
    session_start();
    $_SESSION[pid]++;
    echo "top page $_SESSION[pid]";
    echo "<BR><a href='secondary.php?pid=$_SESSION[pid]'>secondary page</a>";
?>

Secondary page (file secondary.php):

<?php
    session_start();
    if ($_SESSION[pid] != $_GET[pid]) 
        header("location: top.php");
    else {
        echo "secondary page $_SESSION[pid]";
        echo "<BR><a href='top.php'>top</a>";
    }
?>

The effect is to allow navigating from the top page forward to the secondary page and back (e.g. Cancel) using your own links. But, after returning to the top page the browser back button is prevented from navigating to the secondary page.

Littm
  • 4,923
  • 4
  • 30
  • 38
0

Instead of trying to disable the browser back button it's better to support it. .NET 3.5 can very well handle the browser back (and forward) buttons. Search with Google: "Scriptmanager EnableHistory". You can control which user actions will add an entry to the browser's history (ScriptManager -> AddHistoryPoint) and your ASP.NET application receives an event whenever the user clicks the browser Back/Forward buttons. This will work for all known browsers

Corne
  • 646
  • 1
  • 6
  • 19
0

Even I faced the same situation before...and didn't have any help. try these things maybe these will work for you

in login page <head> tag:

<script type="text/javascript">
    window.history.forward();
</script>

in Logout Button I did this:

protected void Btn_Logout_Click(object sender, EventArgs e)      
{
    connObj.Close();
    Session.Abandon();
    Session.RemoveAll();
    Session.Clear();
    HttpContext.Current.Session.Abandon();
}

and on login page I have put the focus on Username textbox like this:

protected void Page_Load(object sender, EventArgs e)
{
    _txtUsername.Focus();
}

hope this helps... :) someone plz teach me how to edit this page...

Austin
  • 154
  • 4
  • 20
Robin
  • 471
  • 6
  • 18
  • a) edit your answer b) click on the question mark c) click on advanced help d) read and apply :-) Also note that ctrl-k un/indents the selected block to un/format as code. Plus the formatter can't handle tabs well (probably not a problem here, though) – kleopatra Mar 14 '13 at 10:18
0

IF you need to softly suppress the delete and backspace keys in your Web app, so that when they are editing / deleting items the page does not get redirected unexpectedly, you can use this code:

window.addEventListener('keydown', function(e) {
  var key = e.keyCode || e.which;
  if (key == 8 /*BACKSPACE*/ || key == 46/*DELETE*/) {
    var len=window.location.href.length;
    if(window.location.href[len-1]!='#') window.location.href += "#";
  }
},false);
nvd_ai
  • 1,060
  • 11
  • 20
0

Try this code. You just need to implement this code in master page and it will work for you on all the pages

<script type="text/javascript">
    window.onload = function () {
        noBack();
    }
    function noBack() {
        window.history.forward();
    }
</script>
<body  onpageshow="if (event.persisted) noBack();">
</body>
Suhaib Janjua
  • 3,538
  • 16
  • 59
  • 73
0

The problem with Yossi Shasho's Code is that the page is scrolling to the top every 50 ms. So I have modified that code. Now its working fine on all modern browsers, IE8 and above

var storedHash = window.location.hash;
function changeHashOnLoad() {
    window.location.href += "#";
    setTimeout("changeHashAgain()", "50");
}

function changeHashAgain() {
    window.location.href += "1";
}

function restoreHash() {
    if (window.location.hash != storedHash) {
        window.location.hash = storedHash;
    }
}

if (window.addEventListener) {
    window.addEventListener("hashchange", function () {
        restoreHash();
    }, false);
}
else if (window.attachEvent) {
    window.attachEvent("onhashchange", function () {
        restoreHash();
    });
}
$(window).load(function () { changeHashOnLoad(); });
Community
  • 1
  • 1
Vishnu T S
  • 105
  • 8
0

This seems to have worked for us.

history.pushState(null, null, $(location).attr('href'));
window.addEventListener('popstate', function () {
    history.pushState(null, null, $(location).attr('href'));
});
jgabb
  • 542
  • 1
  • 4
  • 20
0
<script>
    $(document).ready(function() {
        function disableBack() { window.history.forward() }

        window.onload = disableBack();
        window.onpageshow = function(evt) { if (evt.persisted) disableBack() }
    });
</script>
Chetan
  • 132
  • 1
  • 8
0

You should be using posts with proper expires and caching headers.

epascarello
  • 204,599
  • 20
  • 195
  • 236
  • See my comment on [this answer](http://stackoverflow.com/questions/961188/disable-browsers-back-button/961214#961214) for why that doesn't work. – thomasrutter May 18 '11 at 00:50