31

I am trying to handle browser back button event but i could not find any solution.

I want to ask user if he clicks on browser back button using "confirm box" if he chooses ok i have to allow back button action else i have to stop back button action.

Can any one help me in implementing this.

Ramesh Paul
  • 840
  • 4
  • 15
  • 31
  • 1
    http://stackoverflow.com/questions/1589478/strategies-for-preserving-form-data-on-tab-browser-close – Paul Jan 27 '13 at 00:48
  • This was possibly already answered in [this thread](http://stackoverflow.com/questions/1704533/intercept-page-exit-event) – TildalWave Jan 27 '13 at 00:49
  • Your question is either how to implement history buttons in JavaScript, or that TildalWave and Paul mentioned. – ssice Jan 27 '13 at 00:52
  • As TildalWave and Paul mentioned but i want to handle only back button event not page reloading and page closing events. – Ramesh Paul Jan 27 '13 at 00:58
  • research `onbeforeunload`, start in [MDN docs](https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload) Not sure what you are thnking but back button initiates page close event and that is all you can work with – charlietfl Jan 27 '13 at 01:42

2 Answers2

34

Warn/confirm User if Back button is Pressed is as below.

window.onbeforeunload = function() { return "Your work will be lost."; };

You can get more information using below mentioned links.

Disable Back Button in Browser using JavaScript

I hope this will help to you.

Sampath
  • 63,341
  • 64
  • 307
  • 441
  • 2
    This solution works only for IE browser but it does not works on Chrome and Firefox browser. Can any one please provide special JS scripts so that we can handles the back button on all browsers.... – Bhanuprasad Kunde Aug 29 '13 at 16:54
  • 4
    @BhanuprasadKunde - You are mistaken when you say that onebeforeunload only works with IE. It works with IE,FF,chrome and Opera. Check for implementation errors in javascript console. – Srihari Aug 29 '13 at 17:23
  • 1
    can confirm, `window.onbeforeunload` works also in Chrome, FF (Opera? - i dont test it) – psulek Apr 29 '14 at 09:42
  • This only works in Firefox if you have interacted with the website – ChewToy May 02 '16 at 11:51
  • Second link "Mastering_The_Back_Button_With_Javascript" seems to be dead – Cyril Duchon-Doris Jan 09 '17 at 19:09
  • Yes,you're right.I have removed that link.Thanks :) @CyrilDuchon-Doris – Sampath Jan 10 '17 at 01:09
14

You can also add hash when page is loading:

location.hash = "noBack";

Then just handle location hash change to add another hash:

$(window).on('hashchange', function() {
    location.hash = "noBack";
});

That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.

Szorstki
  • 1,374
  • 1
  • 10
  • 17