0

I have this script in my aspx page

<script language="JavaScript" type="text/javascript">     
    window.onbeforeunload = function(e) {
        return 'Bye now!';
    }; 
</script>

But this is not invoked when I close the browser. I need to pop an alert asking the user to confirm. I need to do this in the aspx page using javascript. The browser I tried was mozilla firefox. Thanks

Shawn31313
  • 5,978
  • 4
  • 38
  • 80

1 Answers1

1

The following code should fix your issue:

(function () {
    window.unloader = function(e) {
       (e || window.event).returnValue = null;
       return null;
    };
    window.addEventListener("beforeunload", window.unloader);
})();

You are not going to be able to specify a message, it is defaulted by the browser.

Shawn31313
  • 5,978
  • 4
  • 38
  • 80
  • It is working only with IE. Not with firefox and chrome –  Nov 07 '17 at 05:06
  • It works on all platforms. I use this exact code everywhere I need it. The wrapper I added might help.. – Shawn31313 Nov 07 '17 at 05:08
  • With firefox the alert pops up for the first time and If I Click Leave this page. The next time when I open it again and close it the pop up does not occur. But when I open it for the third time and close it the pop up occours. Have you faced something like this –  Nov 07 '17 at 05:11
  • Where are you testing this? Because JSFiddle and other development environments might not allow this. @SamDaniel – Shawn31313 Nov 08 '17 at 03:15
  • I did this using VS 2012 –  Nov 08 '17 at 04:34