109

How to ask confirmation from user before he leaves the page as in gmail?

I searched for this question in various places, but all that they mention is the use of javascript window.unload & window.onbeforeunload. Also it doesn't work in chrome most of the times as it gets blocked.

  • I tried window.unload & window.onbeforeunload but they didn't work as required. –  Apr 25 '12 at 07:42
  • 3
    @CiroSantilli: No, it's not. That other question is about issues with using `onbeforeunload` correctly – Bergi Jul 11 '14 at 00:44

9 Answers9

152

Try this:

<script>
window.onbeforeunload = function (e) {
    e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = 'Sure?';
    }

    // For Safari
    return 'Sure?';
};
</script>

Here is a working jsFiddle

gopi1410
  • 6,567
  • 9
  • 41
  • 75
  • 2
    also this wont be disabled by any browser since it originates from user click – gopi1410 Apr 25 '12 at 07:45
  • Thanks a lot! this is what I needed. btw, love the fiddle demo, exactly what I wanted. –  Apr 25 '12 at 07:46
  • Hi..your code is working but it can't differentiate whether user has clicked the close button of browser or clicked the navigation button to go to some other page. – user3217843 Oct 07 '16 at 09:44
  • The OP didn't ask specifically for that. If you need that I guess you need to check `event.target` and check if the click event originated from you page container. – gopi1410 Oct 07 '16 at 10:03
  • Page container as in ? – user3217843 Oct 07 '16 at 10:05
  • Everything in your tag or a specific div if you're targeting something else – gopi1410 Oct 07 '16 at 10:51
  • if i do like this than i have to write same script on each page and have to specify the button name or something that tell to my java script that the event is generated within the page right? – user3217843 Oct 07 '16 at 11:47
  • @gopi1410 - Can I add my own javascript code instead of this confirmation box? – Musaddiq Khan May 18 '17 at 09:46
  • Any specific method to use only on browser or tab close action rather than using on navigation ? – dipak_pusti May 24 '17 at 06:38
  • @MusaddiqKhan not sure – gopi1410 May 24 '17 at 12:19
  • how to run this cod in fiddle, not working in my case/ – Irfan Nasim Nov 09 '17 at 06:10
  • 12
    I tried and it works only if something else is clicked first eg. a link has been right clicked. Then if I click the browser close button it prompts before closing as expected. Otherwise if I go directly to the page for example and click close button straightaway it doesn't work and page closes. The code inside onbeforeunload function hits each but in the last case clearly has no effect. – nickornotto Feb 15 '18 at 14:33
  • Showing a prompt isn't guaranteed. Just like playing audio on the web, browsers can ignore your request if a user hasn't interacted with your page. As a user, imagine opening and closing a tab that you never switch to—the background tab should not be able to prompt you that it's closing. – mav-raj Jan 27 '20 at 11:14
  • 1
    This code is used to work in the old days (posted in 2012) and not working in most of the browsers now due to security issues. – Kapila Perera Mar 04 '20 at 17:28
  • Is this code is working in 2021? I tried but not working – user9437856 Jan 13 '21 at 12:06
  • I found much better this solution: https://stackoverflow.com/a/2858115/2132157 because it only respond to tab closing not internal links. – G M Apr 16 '21 at 10:51
15

Try this:

<script>
    window.onbeforeunload = function(e) {
       return 'Dialog text here.';
    };
</script>

more info here MDN.

Claudia L
  • 191
  • 1
  • 5
  • Note that now the official documentation linked here mentions this way: addEventListener("beforeunload", (event) => {}); – Valerio Bozz Mar 27 '23 at 11:07
15

The shortest solution for the year 2020 (for those happy people who don't need to support IE)

Tested in Chrome, Firefox, Safari.

function onBeforeUnload(e) {
    if (thereAreUnsavedChanges()) {
        e.preventDefault();
        e.returnValue = '';
        return;
    }

    delete e['returnValue'];
}

window.addEventListener('beforeunload', onBeforeUnload);

Actually no one modern browser (Chrome, Firefox, Safari) displays the "return value" as a question to user. Instead they show their own confirmation text (it depends on browser). But we still need to return some (even empty) string to trigger that confirmation on Chrome.

More explanations see on MDN here and here.

Konstantin Smolyanin
  • 17,579
  • 12
  • 56
  • 56
7

I read comments on answer set as Okay. Most of the user are asking that the button and some links click should be allowed. Here one more line is added to the existing code that will work.

<script type="text/javascript">
  var hook = true;
  window.onbeforeunload = function() {
    if (hook) {

      return "Did you save your stuff?"
    }
  }
  function unhook() {
    hook=false;
  }

Call unhook() onClick for button and links which you want to allow. E.g.

<a href="#" onClick="unhook()">This link will allow navigation</a>
Musaddiq Khan
  • 1,837
  • 18
  • 16
6

Simply

function goodbye(e) {
        if(!e) e = window.event;
        //e.cancelBubble is supported by IE - this will kill the bubbling process.
        e.cancelBubble = true;
        e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog

        //e.stopPropagation works in Firefox.
        if (e.stopPropagation) {
            e.stopPropagation();
            e.preventDefault();
        }
    }
window.onbeforeunload=goodbye;
Dev Matee
  • 5,525
  • 2
  • 27
  • 33
3

If you want to ask based on condition:

var ask = true
window.onbeforeunload = function (e) {
    if(!ask) return null
    e = e || window.event;
    //old browsers
    if (e) {e.returnValue = 'Sure?';}
    //safari, chrome(chrome ignores text)
    return 'Sure?';
};
yaya
  • 7,675
  • 1
  • 39
  • 38
  • Thank you. This answer can be appreciated because it is very similar to the cross-platform solution suggested here: https://developer.mozilla.org/en-US/docs/Web/API/BeforeUnloadEvent – Valerio Bozz Mar 27 '23 at 11:21
0
  1. Let say i want to close a window if nothing is selected
  2. I want to close window with something selected but don't prompt me.
  3. I want to close a window but something is selected prompt me plz.

For these three conditions I have searched a lot in the following code made changes suit my needs hope help someone else. ask is a key if I want to pop up the prompt 'true' will prompt you for close window other wise not. Suppose I want to print my document and redirect my page the ask will be false and there will be no prompt. Suppose your page having data then check a condition is my case a value subtotal if subtotal is zero then no prompt other wise prompt me that you have something in your page.

<pre>
    var ask = true;
    window.onbeforeunload = function(e) {
       if (!ask) return null
       var subtotal = $('#lblgtwithsgst').text();
         if (subtotal != '0') {
          e = e || window.event;
          //old browsers
            if (e) {
             e.returnValue = 'Sure?';
            }
            //safari, chrome(chrome ignores text)
            return 'Sure?';
         }  
      }
      $('#btnPrint').click(function(){
        ask = false;
        ///print your doc no prompt if ask is false;
      )};
khan ss
  • 1
  • 2
-2
// use jquery version older than 1.6
var preventUnloadPrompt;
var messageBeforeUnload =
  'my message here - Are you sure you want to leave this page?';
$('a').live('click', function () {
  preventUnloadPrompt = true;
});
$('form').live('submit', function () {
  preventUnloadPrompt = true;
});

$(window).bind('beforeunload', function (e) {
  var rval;
  if (preventUnloadPrompt) {
    return;
  } else {
    return messageBeforeUnload;
  }

  return rval;
});
Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 09 '21 at 13:10
-2

For Angular, Change with component form name and paste in component where you need to display alert.

  @HostListener('window:beforeunload', ['$event'])
  beforeunloadHandler(event) {
    return !this.form.dirty;
  }
Mitesh
  • 71
  • 12