Disable Back Button in Browser using JavaScript

[ad name=”AD_INBETWEEN_POST”] Sometimes we have requirement in developing a website to disable the Back button effect from Browser. This is common in Online Banking Websites and other sites where security is of principal concern. User may hit back and navigate from the page and forget to logout. Hence sometime it is required that we disable the functionality of Back button. But unfortunately this is not an easy task. There is no direct way of dealing with this problem. We can do few hacks to ensure that user does not get back in the browser. Following are few tricks that can be used to disable the back button in browser. Please note that we do not literally “disable” the back button, but just nullify its effect is some case and hide it altogether in others. disable-back-button-browser

Open A New Window without Back Button

browser-back-button-viralpatelThis one is very crude technique. But in some case it works like charm. All you have to do is to open the webpage in a new window. This window doesn’t have back button at all because we have hide the toolbar. This technique does work in some case but user has still a workaround to navigate to previous page. Most of the browser have options of Back in context menu. Thus user can still right click on the page and click Back to go to previous page. We will shortly see the workaround for this issue also. Following is the code to open webpage in a new window have no toolbar (Back/Next buttons).
window.open ("https://www.viralpatel.net/", "mywindow","status=1,toolbar=0");
Code language: JavaScript (javascript)
Also it is possible to disable the right click on any webpage using Javascript. Add following code in the webpage.
<body oncontextmenu="return false;">
Code language: HTML, XML (xml)

Disable Back functionality using history.forward

This is another technique to disable the back functionality in any webpage. We can disable the back navigation by adding following code in the webpage. Now the catch here is that you have to add this code in all the pages where you want to avoid user to get back from previous page. For example user follows the navigation page1 -> page2. And you want to stop user from page2 to go back to page1. In this case all following code in page1.
<SCRIPT type="text/javascript"> window.history.forward(); function noBack() { window.history.forward(); } </SCRIPT> </HEAD> <BODY onload="noBack();" onpageshow="if (event.persisted) noBack();" onunload="">
Code language: HTML, XML (xml)
The above code will trigger history.forward event for page1. Thus if user presses Back button on page2, he will be sent to page1. But the history.forward code on page1 pushes the user back to page2. Thus user will not be able to go back from page1.

Warn User if Back is Pressed

You may want to warn user if Back button is pressed. This works in most of the cases. If you have some unsaved form data, you might want to trigger a warning message to user if Back button is pressed. Following Javascript snippet will add a warning message in case Back button is pressed:
window.onbeforeunload = function() { return "You work will be lost."; };
Code language: JavaScript (javascript)
Include this in your HTML page to popup a warning message. Check the demo for this example. ONLINE DEMO
Get our Articles via Email. Enter your email address.

You may also like...

130 Comments

  1. This is really cool. I have posted it in DZone. Thanks for your time involved.

  2. Harika Rai says:

    How to delete cookie history on a sign out and not allowing back functionality by using javascript

  3. Nonye Ulasi says:

    Hi Viral,
    Thanks for the above code however, using the window. history.forward() function to disable the back browser works well on IE and Opear, but not on Safari and google chrome. Do you know why this is, and if so, could you supply some javascript code that will work on all browsers?
    Many Thanks
    Nonye

  4. sweta says:

    really good

  5. Manoj says:

    Hi Viral,
    Not working for Google chrome. Can you please give javascript code that will work on all browsers?
    Many Thanks

  6. see http://www.boutell.com/newfaq/creating/backbutton.html -use setTimeoutto delay call to forward. -should help for other browsers

  7. padma says:

    Only IE its working not in all browsers

  8. sathish says:

    but it is not working for Google chrome

  9. Mayur says:

    Read the below article :
    excellent one :
    The code works for IE 7, Chrome 4.1, Firefox 3.6.3
    http://www.boutell.com/newfaq/creating/backbutton.html

  10. thanks for this useful article. best regards.

  11. jeterboy says:

    hey thanks for this.

  12. Shobhraj says:

    Thanks….good content…

  13. vikash says:

    ////Open A New Window without Back Button//

    This method is not working in IE-7
    plz help me out

  14. amit says:

    this is not working

  15. Amit Herlekar says:

    Many thanks

  16. vishnu says:

    hi,
    Thanks….good answer
    But using PHP, how to prevent clicking the browser back button for authenticated pages

  17. Pavan says:

    Thanks this code works fine that disable to go back the previous page.

  18. Rubesh says:

    Not So Effective For me……………………………….!

  19. Azhar says:

    Hi..Thank you very much. It has helped me alot:)

  20. KAIALSH says:

    Hi Viral Sir i liked ur code of Itext to generate PDF also.This one is also cool!!Thanks a lot!

  21. divya says:

    Thanks a ton!!!
    Its kindly helpful for me..
    I knew “window.history.forward”
    but i was not frequent with javaScript so unable to use properly

    but ur article really helped me out!!!

    I want to ask you one more thing..
    if u wil reply then i wil ask something

    THANKSSS!!! :-)

  22. aadi says:

    Hey ,

    Thankz

    Its 2 good

  23. Dumindu says:

    Thanks

  24. salumiah says:

    excellent…
    am using this code in webpages…
    thankyou

  25. balaji says:

    thank you for the code

  26. Shishir says:

    Cool….. Thankyou so much…

  27. tito says:

    thanks so much

  28. This is really works… I got solution…
    Thanx Viral for posting this….

  29. DineshKumar says:

    Good Work… :)
    Thanks a lot….

  30. jim says:

    thanks

  31. ved says:

    buddy..i am working on a project and i need to disable the back button,but after my all stuffs i am still unable to do this..i don;t know why it is not working in my running project ,instead it is working in other of my team mate’s project .
    could you please tell me ,am i doing some thing wrong? why it is not working.

  32. Nandha says:

    Sorry My friend this code not work in Chrome

    • @Nandha – I just tried the demo in Chrome. It worked perfectly. Please check again.

  33. sridhar says:

    thanks alot

  34. smruti says:

    Nice.Thank You so much

  35. Joseph Elisha Bañez says:

    Thanks for the code! :)

  36. satyajit says:

    thanks….It works perfectly..

  37. aditia says:

    thanks it really help

  38. biju says:

    really nice!!!thank you…….

  39. Rajendra & Sumit says:

    Thanks Yar its Works……..

  40. satish says:

    when i press back button using mouse then browser shows all the history of that particular tab.
    Please help me.

  41. Kranthi says:

    Good job

  42. CAMILLE says:

    I tried your online demo but it did not work with my version of IE8. I was allowed to use the back button.

  43. swarnima says:

    thank you so much! It really worked well!!

  44. vimal says:

    thanks…Its really a very nice code…
    Great work…

  45. hisoka says:

    thanks .. worked perfectly
    but how can i make it navigate to an expired page instead of going to the same page

  46. Mukund says:

    It’s really Excellent Article

    Your Code is Really Compitable in almost all modern browser including IE, FireFox, Opera, Chrome etc.

    But I have a ?

    How to disable browser back button using server side code in asp.net using session

    Because I am using Master Page in my project

    So i can’t implement to your javascript code to disable backbutton in Master Page

    Because It will disable all web page back button so I need only to disable back button after signout/logout page

  47. R.J. Karthikbabu says:

    Hai.. Sir. This coding only worked on IE.

  48. omi says:

    i have used your code in my project..it was working fine..but when i was holding my mouse over the back button in google chrome it shows the history and from that it was possible for me to go back to the previous page..can you plz tell me some other permanent solution..so that the back button is completely disabled for a particular page..

  49. planetjane414 says:

    Good job!
    Thank’s a lot! :)

  50. jaisal says:

    Thanks , its good , great

  51. Raja says:

    Thanks Dude

  52. Hardik Soni says:

    Hi
    This script is not working in safari.

    I am checking it on safari 5.1.7.

    Please have a look at it.

    Thanks

  53. Prajakta says:

    Its not working with function onbeforeunload()
    Is there any way to disable back button?

    • Nils says:

      To disable browser’s back button “window.history.forward();” is enough, isn’t it ?
      Why do we need all other code ?
      Plzz reply fast…

      • Nils says:

        Oppps! it wasn’t for you but to the post…How did it go there ?

  54. yuda says:

    thanks for help ^^

  55. Hardik Soni is correct – this doesn’t work in Safari.

    • Aniruddh says:

      It does not work in safari browser because safari does not support things like window.history() and window.go() , similerly data-rel attribute is also unreliable. We can use 4mobile.Changepage() call in that case by getting pageId/url of previous page in that case

  56. Sashank Raj says:

    So, much thank you.

  57. Murthy says:

    Excellent article. But my problem is how to avoid the back button from the current page. For e.g. after session expires, it will be redirected to “sessionexpiredpage.aspx”. If user is trying to click on back button it should not go back, it should stay in the same page and user will forcefully close the browser. Appreciate if you can provide the code to handle this.

    Thanks a ton.

    • Prabhu says:

      Paste that javascript in pages to which you don’t want to come back again no matter what.
      Suppose Page1 is idle and redirected to Expiry Page, paste the code in Page 1 to avoid coming back to Page 1 using browser’s back button

  58. mudassir says:

    superb

  59. Scott Joplin says:

    Anyone who disables the back button of a browser is scum. Why would you want to intentionally make the internet harder for people to use? Are you trying to ensure that repeat traffic on your website is zero?

    You’re an idiot if you use this feature. A properly designed website will never, for any reason, need this feature. You’re an amature

    • Brandon says:

      Hi Scott,

      Everyone is entitled to their opinion, but this doesn’t only apply to the “Internet”. What if you have a web-based application (internal to your company) running on JVMs? Many web-based applications throw Java exceptions which cannot be handled when the back/refresh buttons are pressed. This action leads to null pointer exceptions in the application log, and rapid generation of many spurious objects within JVM memory, which Garbage Collection then struggles to delete. This in turn can lead to the JVM memory being maxed out, causing major performance issues and/or outages. Sounds to me like you’re the amateur…and that goes for your spelling as well.

      • dragunov says:

        Hi Scott,

        And sometimes due to security reason to protect data or system/application flows. Not everything is about traffic :)

    • ravi says:

      this is very much useful when dealing with form data where inserted data get lost so in order to prevent this is used.

  60. Steve says:

    Thank You so so so much dude..im a noob at this stuff and been looking for this lol

  61. I remember I needed this for a Drupal website I was building a few years ago. Fortunately, we found a Drupal Module to do the trick.

  62. Giuseppe says:

    Followinganother solution without using window.history:

    <script type="text/javascript">
    	function clickLink() {
    		document.getElementById("link").click();
    	}
    	
    </script>
    
    <body onload="clickLink()">
    		
    <a id="link" href="page2.html" />
    
    </body>
    

    • Afzal says:

      Thanks dude…

  63. vivek yadav says:

    Dude you are great and i truely repect you.

  64. Ayush says:

    This is working like a charm. Thanks a lot. Now do you know how to disable the forward as well.
    Thanks a billion.

  65. kkkkkkkkk says:

    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);

  66. Thirunavukarasu says:

    Thank you so much …. Mr.Viral Patel

  67. Arnold says:

    Thanks Viral for sharing this. The fact that I have landed here, means I was looking for help. Those of you demeaning these solutions will one day come back to this site. There are so many practical reasons for these requirements.

  68. Ashish says:

    Thanks … Viral your post saved a lot of time ….

  69. Praveen says:

    This was of excellent help.
    Thanks for posting it .

  70. shoiyab says:

    Thanks

  71. sam says:

    thanks dude …….
    this really wark

  72. sam says:

    hi
    my query is
    i create a table in mysql5.5 create table data(id int NOT NULL AUTO_INCREMENT ,user varchar(30),pass varchar(20),PRIMARY KEY(id)) ENGINE=MyISAM;
    but id is not auto increment plz resolve this problem …………….

  73. pooja says:

    thanks …….
    this code really works and my prob. is easily solved by this code.

  74. pankaj wanajri says:

    Cool tricks ……….it works perfectly for me .
    Thanks buddy .

  75. pooja says:

    I m using the code given below n this is not working so can anybody tell me what is the problem in this code

    <script type="text/type">
    window.History.forward();
    </script>
    <%response.setHeader("Pragma","no-cache");
       response.setHeader("Cache-control","no-store");
       response.setHeader("Expires","0");
       response.setHeader("Expires","-1");%>
    

  76. Sweety says:

    I m using the code given below n this is not working so can anybody tell me what is the problem in this code

    window.History.forward();

  77. Vamsi says:

    Thank u very much its working…. i solved my problem.

  78. Arpit Totla says:

    Thank u…great work…

  79. pranay godha says:

    Thank you. it helped me.

  80. Gulshan says:

    Thanx…very helpful

  81. jiju says:

    nice..very helpful

  82. ravi says:

    Thanks you. Very helpful :)

  83. nisha says:

    i wanna such code for only single page not for entire pages. this code is working finely in entire pages not in single page. how will i do when i logout the page comletely then i click on back button nothing shoud b happen there. i can’t put these code in entire pages. i wanna such a script which we keep within logout page…….

  84. prapoorna says:

    Thank you so much.. you helped me a lot, it is working for browser back button and working fine for right click on browser’s back button too.

    • Deeksha says:

      Hi prapoorna
      Is your functionality working when you pressed back button twice or more than once?
      If yes can you please provide the solution for this?

  85. Deeksha says:

    Thanks Viral Your solution is working fine for me.But its working only when i click Back Button first time.When i click it twice then am getting “webpage Expired” .
    Any Solution to this Problem??

  86. joker says:

    thanks

  87. yunus says:

    Thanks viralpatel
    It’s really helpful n it works!

  88. jay says:

    How to disble user in ACL spring security…

  89. Aro says:

    Thanks dude

    help me alot

  90. thanku thanku thanku very much…….. its working dude

  91. dario says:

    Thanks!

  92. bhavana khatri says:

    this code is not work for me in my site.

  93. bhavana khatri says:

    One More Solution on Pageload of Master page

    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1))
    Response.Cache.SetNoStore()

  94. Anshul says:

    not working :(

  95. Ranjan says:

    I am a regular subscriber ….

    disable back button in jsp is not working,..Kindly suggest

  96. sam says:

    IT WORKS JUST LIKE ‘Viral Patel’ SAY’S.

  97. franco says:

    how to redirect to a different page if press back botton or refresh a page?

  98. bhargav says:

    hai i liked it.but i want this to happen only when click on logout button only.
    plz help

  99. Lawrence says:

    Thanks Boss!!

  100. sushma says:

    Hi i have a question, I am performing a research were i am required to disable back button. I tried your code and its working fine. but i have a timer in my second page so whenever user clicks back button in page 2 it comes back from page 1 with timer starting again. Do my question is how do i save my current state. Please guide. Appreciate your help

  101. Pavan says:

    Thanks that worked

  102. As far as I can tell, you do not need the

    noBack()

    function.
    You simply need to put :

    window.history.forward();


    on the page to which you would not like a history based navigation (the “Back” button in a browser).
    This works in IE8-11, FireFox, Chrome, Opera (all I tested).

    Also, it is much trickier to use the

    window.onbeforeunload

    event because it happens for many more things (like closing the window, forward button, etc) than simply the browser back button. If you are simply trying to make sure a user does not navigate away, it may work for you, but it by no means the equivalent of trapping the “Back” button.

    Thanks!
    -w

  103. nice tutorial. but does it work in all browsers.

  104. Lawakush Kurmi says:

    i have used this code to block (disable) back press on browser but when im clicking more than one time and pressing esc button (keyboard) then it sends to back page. what ‘s happining there pls suggest me any better solution.

  105. sudip says:

    Its works nicely but if you disable the back button then its look more good.
    Another thing i want to know how can I show the “session is expire” after click the logout In PHP . Plz help

  106. Amit says:

    Hi,

    Pls provide me example code for warning message when user clicks back button in jsp.
    or
    code for window.onbeforeunload that where to use it.

    Thanks in advance

  107. salimmejdoub says:

    hello i use jquery mobile
    and sorry i did not work for me what i should do
    thanks

  108. Santhosh K S says:

    Hi viral,
    Please post ONLINE DEMO code. u r post is very useful.

  109. vikas kumar says:

    Perfect, it working. Thanks very much. its very useful.

  110. sin says:

    Hey..!!! that worked and solved my one week’s issue…Thanks..good one!! :)

  111. John says:

    Is it possible to delete the client browser history and cache via js

  112. Dhana Shekar says:

    Thank you Viral:-)

  113. Kavivarman says:

    Thanks a lot to all….

  114. Yohan Dedik Irawan says:

    Thanks a lot… This solve my problem.

  115. Ziaul Kamal says:

    how to mix a content to random post if user click back button browser ?

    mail to me;;;;

  116. model rumah says:

    hay, i wist try ini blogspot, but not work, can you give mu advice ??
    thansk

  117. berbagi73 says:

    Where should I place the code?

  118. Priya says:

    Its good. How can I achieve this functionality in angular 6

Leave a Reply

Your email address will not be published. Required fields are marked *