Confirmation before closing of tab/browser

JavascriptHtml

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

Try this:

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

more info here [MDN][1]. [1]: https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#Example

Solution 3 - Javascript

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>

Solution 4 - Javascript

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.

Solution 5 - Javascript

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;

Solution 6 - Javascript

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?';
};

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1349661View Question on Stackoverflow
Solution 1 - Javascriptgopi1410View Answer on Stackoverflow
Solution 2 - JavascriptClaudia LView Answer on Stackoverflow
Solution 3 - JavascriptMusaddiq KhanView Answer on Stackoverflow
Solution 4 - JavascriptKonstantin SmolyaninView Answer on Stackoverflow
Solution 5 - JavascriptMatee GojraView Answer on Stackoverflow
Solution 6 - JavascriptyayaView Answer on Stackoverflow
Solution 7 - Javascriptkhan ssView Answer on Stackoverflow
Solution 8 - JavascriptSoumyajit GiriView Answer on Stackoverflow
Solution 9 - JavascriptMiteshView Answer on Stackoverflow