33

I want to disable the back button for a website.

Whenever the person clicks on the browser back button it should not be able to go on the page the user visited before.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
A Beginner
  • 447
  • 1
  • 6
  • 11
  • 9
    (a) Such a horrible idea from a usability perspective. (b) See: http://stackoverflow.com/questions/12381563/how-to-stop-browser-back-button-using-javascript – Ayush Nov 12 '13 at 10:29
  • 3
    You simply cannot and should not do this. However, you might find the [`unload` event](https://developer.mozilla.org/en-US/docs/Web/API/Window.onunload) useful. – Boaz Nov 12 '13 at 10:35
  • 22
    there is a time, place, and need for everything. but the haters have to hate. I could list a bunch of reasons in today's ajax powered web apps where this would be necessary. – pathfinder Jan 29 '15 at 15:43
  • try this , a different approach http://geekswithblogs.net/Frez/archive/2010/05/18/back-button-issue-after-logout-in-asp.net.aspx – Syed Mohamed Feb 11 '15 at 15:35
  • also refer http://stackoverflow.com/a/28458499/2089963 – Syed Mohamed Feb 11 '15 at 15:48
  • window.history.forward(1); – Sreekanth Karini Jul 25 '16 at 07:00
  • Voting to reopen as answers here provide updated info regarding this topic (new answers on this other page would be buried at the bottom). This Q&A supersedes the old one. – Déjà vu Feb 18 '17 at 07:06

4 Answers4

265
history.pushState(null, null, document.title);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.title);
});

This script will overwrite attempts to navigate back and forth with the state of the current page.


Update:

Some users have reported better success with using document.URL instead of document.title:

history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.URL);
});
rinogo
  • 8,491
  • 12
  • 61
  • 102
Shailendra Sharma
  • 6,976
  • 2
  • 28
  • 48
  • This is what I'm looking for. It works on Chrome, IE11 and the iPad's Safari. Someone down-voted it regardless of its usefulness. – jaselg Sep 29 '14 at 03:37
  • Would this also affect the browser's back button? – wasabigeek Jul 03 '15 at 10:42
  • I ended up doing this: onpopstate = function (event) { window.location.hash = ''; return(null); }; It works for me as I expect, but this answer helped me understand what I should do. – dhruvpatel Dec 30 '15 at 17:28
  • It worked just as explained but I needed to specify pagename as ' ' otherwise I got the page name in the URL. I placed this code in a layout page, common to all others and maybe that is the reason. – nrod Jan 25 '16 at 13:23
  • The reason this is getting downvotes is because disabling standard browser functionality is about the *worst UX practice that exists*. However, the answer itself is the correct answer to the question, meaning this answer should technically be upvoted. – dudewad Jan 26 '16 at 17:51
  • It works on Firefox too – Tony Dong May 14 '16 at 19:23
  • 9
    Downvoting : as it changes the URL and due to which site crashes on refresh. – Mohan Seth May 30 '16 at 13:50
  • Works like a charm window.addEventListener('popstate', function () { var hash = computePageHash(); if (hash != $('#PAGE_STATE').val()) { alert('You have unsaved changes!'); history.pushState(null, null,'#'); } else { history.back(); } }); $(document).ready(function () { history.pushState(null, null, '#'); savePageHash(); }); – Vishnoo Rath May 31 '16 at 09:35
  • 14
    @Mckenzie the URL is changed because of history.pushState(null, null, document.title); statement. It puts title of the page in the URL and this causes the crash on refresh. You can replace **document.title** with your page URL. This will solves your issue. Before downvoting please try to understand the code. It's one of the best solutions I found so far. – Arjun Ajith Jun 13 '16 at 10:26
  • @ArjunAjith Please could you show us how to replace document.title for the site url ?? – jsanchezs Jun 13 '16 at 19:52
  • @jsanchezs The code will change only the last part of the URL. Here it is changed with document.title parameter which provides title of the page. Just change it with the orginal part. Like change it to 'login' if your orginal URL is www.myadress.com/login – Arjun Ajith Jun 13 '16 at 20:11
  • @jsanchezs Please go through the following link.. This is my modification on the answer. https://stackoverflow.com/questions/10511893/prevent-back-button-after-logout/37786044#37786044 – Arjun Ajith Jun 13 '16 at 20:13
  • @ArjunAjith thanks for your answer, but itś not that easy if my script it's in a base.js from where all templates take reference...i mean, there should be a way to capture the actual url name isn't it ? – jsanchezs Jun 13 '16 at 20:31
  • I used above code and found that there is big problem with the code. But I have also fixed that code by a little change. New code is: history.pushState(null, null, window.location.href); window.addEventListener('popstate', function () { history.pushState(null, null, window.location.href); }); – Alauddin Ansari Jul 18 '16 at 14:55
  • 2
    As @ArjunAjith suggest, I replaced `document.title` with `document.url` and it is working. +1 for this answer. – Adarsh Khatri Aug 02 '16 at 02:48
  • 1
    – Miguel Sep 14 '16 at 09:10
  • This works great, unlike geevee thinks, this is very useful. I am using it on a single page web app so user do not accidentally leave the app when hitting the backspace button and are not on a text input. – Zac Jan 10 '17 at 14:59
  • If you need help setting the document URL go here: https://developer.mozilla.org/en-US/docs/Web/API/Document/URL – AndrewLeonardi Jan 22 '17 at 17:09
  • 2
    To be noted that this doesn't disable long-pressing of the back button. That behaves normally and lets you go back in history. – trss Feb 03 '17 at 21:39
  • any clue on how implement this on angular2? – holyknight Feb 21 '17 at 15:53
  • Great, it work for me. I spent my lot of time to find solution, but this is really work for me. Thanks – gaurav rai Jul 26 '17 at 09:19
  • refresh button is not work correctly. – Madhuka Dilhan Aug 08 '17 at 11:22
  • Not working for me. I put the code in the script tag of the head tag. Any idea why it wouldn't work? – Dov Miller Aug 20 '17 at 10:35
  • Hi, the above solution is not working in ie browser. – N15 Feb 21 '18 at 11:11
  • @ShailendraSharma Sharma in ie it is not working. when I refresh the page it is working – N15 Feb 21 '18 at 11:18
  • 2
    it should be `history.pushState(null, document.title, location.href); window.addEventListener('popstate', function (event) { history.pushState(null, document.title, location.href); });` Reference: https://stackoverflow.com/a/34337617/2073920 – Abdul Rauf Apr 17 '18 at 07:35
24

One cannot disable the browser back button functionality. The only thing that can be done is prevent them.

The below JavaScript code needs to be placed in the head section of the page where you don’t want the user to revisit using the back button:

<script>
    function preventBack() {
        window.history.forward();
    }

    setTimeout("preventBack()", 0);
    window.onunload = function() {
        null
    };
</script>

Suppose there are two pages Page1.php and Page2.php and Page1.php redirects to Page2.php.

Hence to prevent user from visiting Page1.php using the back button you will need to place the above script in the head section of Page1.php.

For more information: Reference

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Joke_Sense10
  • 5,341
  • 2
  • 18
  • 22
-11

Our approach is simple, but it works! :)

When a user clicks our LogOut button, we simply open the login page (or any page) and close the page we are on...simulating opening in new browser window without any history to go back to.

<input id="btnLogout" onclick="logOut()" class="btn btn-sm btn-warning" value="Logout" type="button"/>
<script>
    function logOut() {
        window.close = function () { 
            window.open('Default.aspx', '_blank'); 
        };
    }
</script>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • The browser warns the user that the site is trying to close their page, and they have the option to click cancel...so here we only redirect them if they truly are logging out and leaving the page. – Horizon Consulting Aug 22 '14 at 19:25
  • 1
    use history.pushState() works in all modern browsers which support the HTML5 History API – Shailendra Sharma Sep 04 '14 at 12:26
  • Opening a new window does not have any history for that tab or window and hence this works. but if you want to stay in same window, this is not even close to answering that question. – dhruvpatel Dec 30 '15 at 17:35
  • @dhruvpatel In GNOME’s Epiphany browser, opening new views (tabs/windows) _does_ inherit the history of the parent view. – underscore_d Jan 19 '17 at 09:47
-39

You can't, and you shouldn't.

Every other approach / alternative will only cause really bad user engagement.

That's my opinion.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
geevee
  • 5,411
  • 5
  • 30
  • 48
  • 57
    Let's say you are on an online exam, then it got a little sense. – Sanchitos Dec 23 '13 at 19:27
  • 4
    I think an alert and confirm would work better – Claudiu Creanga Aug 30 '14 at 21:45
  • See Shailendra Sharma's answer for why I voted -1 on this accepted answer. – Greg Nov 17 '14 at 15:33
  • 3
    The most practical example why you **should** be able to do this, is that when clicking the Back button in Firefox, and you have an iframe open that made a history change, the iframe will go back, not the entire page. That's just bull. – Eduard Luca Jan 14 '15 at 10:44
  • 4
    In some cases it is needed. If you were displaying a web view, and had control over browser history, you might wanna disable back button at certain point. Consider a situation in which you are ordering something in web view, if you are not disabling back you might end up in double ordering same thing unnecessarily. – dhruvpatel Dec 30 '15 at 17:12
  • 1
    You are right this is something only bad websites do there is an onbeforeunload event for this. – Filip Cordas May 22 '17 at 12:28
  • If an online exam blocks the back button that way, then that online exam is completley, and utterly worthless. This limitation can be worked around in so many ways it's not even funny (including "without even noticing" ways) – Eric Grange Jun 02 '17 at 06:40
  • 1
    @Sanchitos Or a payment ... – Vinay Dec 01 '17 at 14:50
  • There is a very valid use case for this: When you are designing a web app with partial views and you want to ensure that the app performs expected behavior when the back button is pressed. In that case the back button doesn't actually do what the user might expect unless you provide code for it. "Disabling" it isn't the same, but you are applying the same concept (modifying the behavior of the back button). You can't stop users from clicking back, so you might as well make the app do what they expect. – Lucas Leblanc Nov 14 '18 at 15:29
  • I need to disable it for my customer service reps to create a BETTER experience. If you don't know all the facts, then don't judge the method. – capitalaudience.com Aug 19 '19 at 05:46
  • Please note that your Answer was discussed at meta in [Opinion only answers](https://meta.stackoverflow.com/questions/401844/opinion-only-answers) – Scratte Oct 06 '20 at 15:42